依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>1.8.17</version>
</dependency>
1.8版本对应的代码
通过URL获取的PDF文档
URI certUri = UriComponentsBuilder.fromHttpUrl(certUrl).build(true).toUri();
ResponseEntity<byte[]> certEntity = restTemplate.exchange(certUri, HttpMethod.GET, null, byte[].class);
InputStream reportStream = new ByteArrayInputStream(certEntity.getBody());
try {
// 加载PDF文件
PDFParser pdfParser = new PDFParser(reportStream);
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();
} catch (Exception e) {
e.printStackTrace();
}
2.0版本依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.16</version>
</dependency>
2.0版本对应的代码
URI certUri = UriComponentsBuilder.fromHttpUrl(certUrl).build(true).toUri();
ResponseEntity<byte[]> certEntity = restTemplate.exchange(certUri, HttpMethod.GET, null, byte[].class);
InputStream reportStream = new ByteArrayInputStream(certEntity.getBody());
try {
// 加载PDF文件
PDFParser pdfParser = new PDFParser(new RandomAccessBufferedFileInputStream(reportStream));
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();
} catch (Exception e) {
e.printStackTrace();
}
2.0 与 1.8 版本相比,PDFParser 创建时传的参数类型是不一样的。PDFTextStripper 类的位置也不一样。
https://blog.youkuaiyun.com/weixin_44243466/article/details/118213939