1、导入相关依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>1.8.8</version>
</dependency>
相关依赖可以在https://mvnrepository.com/找到
2、编写测试类
//读取本地文件
File file = new File("C:\\Users\\Administrator\\Desktop\\LINUX_SHELL.pdf");
//加载PDF文件
PDFParser pdfParser = new PDFParser(new FileInputStream(file));
pdfParser.parse();
PDDocument pdDocument = pdfParser.getPDDocument();
//读取文本内容
PDFTextStripper pdfTextStripper = new PDFTextStripper();
//设置输出顺序
pdfTextStripper.setSortByPosition(true);
//起始页
pdfTextStripper.setStartPage(1);
pdfTextStripper.setEndPage(10);
//文本内容
String text = pdfTextStripper.getText(pdDocument);
//换行符截取
String[] split = text.split("\n");
for (String s : split) {
System.out.println("s = " + s);
}
pdDocument.close();
不过目前该依赖只支撑双层PDF文件的读取,暂不支持单层PDF文件读取。