java 获取doc、pdf等文档页数
时间: 2023-12-15 17:03:57 浏览: 180
读取pdf页数jar
可以使用Apache PDFBox库来获取PDF文档的页数,使用Apache POI库来获取Word文档的页数。
获取PDF文档页数的示例代码:
```java
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.File;
import java.io.IOException;
public class PdfPageCount {
public static void main(String[] args) throws IOException {
File file = new File("example.pdf");
PDDocument document = PDDocument.load(file);
int pageCount = document.getNumberOfPages();
System.out.println("Page count: " + pageCount);
document.close();
}
}
```
获取Word文档页数的示例代码:
```java
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.xmlbeans.XmlException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class WordPageCount {
public static void main(String[] args) throws IOException, InvalidFormatException, XmlException {
File file = new File("example.docx");
FileInputStream fis = new FileInputStream(file);
XWPFDocument document = new XWPFDocument(fis);
int pageCount = document.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();
System.out.println("Page count: " + pageCount);
document.close();
}
}
```
阅读全文