前言
有时候会有这样的需求,需要将pdf中的字解析出来,存入库中,查看了一下pdfbox的文档,大概有两种方案。
一、全文解析
当一个pdf中全是文字并且排列规整的时候,直接全文解析出来就好,以下是全文解析代码:
public String getTextFromPdf() throws Exception {
String pdfPath = “pdf文件路径”;
// 开始提取页数
int startPage = 1;
// 结束提取页数
int endPage = Integer.MAX_VALUE;
String content = null;
File pdfFile = new File(pdfPath);
PDDocument document = null;
try {
// 加载 pdf文档
document = PDDocument.load(pdfFile);
// 获取内容信息
PDFTextStripper pts = new PDFTextStripper();
pts.setSortByPosition(true);
endPage = document.getNumberOfPages();
System.out.println("Total Page: " + end

本文介绍了使用PdfBox库解析PDF的两种方法:全文解析和区域解析。在全文解析适合文字排列规整的PDF,而区域解析适用于文字不规整或表格类PDF。通过示例代码展示了如何操作,并建议使用PdfBox 2.X版本,因为新版本在文字位置准确性上有显著提升。
最低0.47元/天 解锁文章
2964

被折叠的 条评论
为什么被折叠?



