java提取pdf对应的目录及页码实践
作者:万能的小帅
这篇文章主要介绍了java提取pdf对应的目录及页码实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
java提取pdf对应目录及页码
添加依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
代码
public static void main(String[] args) throws IOException {
// File file = new File("E:\\navicat.pdf");
File file = new File("C:\\Users\\msi\\Desktop\\max.pdf");
PDDocument document = PDDocument.load(file);
// 获取PDF文件的结构树根对象
// PDStructureTreeRoot structureTree = document.getDocumentCatalog().getStructureTreeRoot();
// 获取PDF文件的文档目录对象
PDDocumentOutline documentOutline = document.getDocumentCatalog().getDocumentOutline();
// 输出目录内容
if (documentOutline != null) {
printOutline(documentOutline, "",0);
}
// 创建PDFTextStripper对象,用于提取文本
// PDFTextStripper pdfStripper = new PDFTextStripper();
// // 提取文本
// String text = pdfStripper.getText(document);
// // 输出文本内容
// System.out.println(text);
// 关闭PDDocument对象
document.close();
}
// 递归输出目录内容
private static void printOutline(PDOutlineNode documentOutline, String indent,int i) throws IOException {
PDOutlineItem item = documentOutline.getFirstChild();
i++;
indent = indent + " ";
while (item != null){
// PDPageDestination destination = (PDPageDestination) item.getDestination();
// int pageNumber = destination.retrievePageNumber();
int pages = 0;
if(item.getDestination() instanceof PDPageDestination){
PDPageDestination pd = (PDPageDestination) item.getDestination();
pages = pd.retrievePageNumber() + 1;
}
if (item.getAction() instanceof PDActionGoTo) {
PDActionGoTo gta = (PDActionGoTo) item.getAction();
if (gta.getDestination() instanceof PDPageDestination) {
PDPageDestination pd = (PDPageDestination) gta.getDestination();
pages = pd.retrievePageNumber() + 1;
}
}
System.out.println("------" +indent + item.getTitle() + "----"+pages+" 层级:"+i );
// 递归处理子项
printOutline(item, indent ,i);
// 获取同级
item= item.getNextSibling();
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
