前言
有时候会有这样的需求,需要将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();