pdfbox读取pdf文档

依赖


    org.apache.pdfbox
    pdfbox
    1.8.17

1.8版本对应的代码

通过URL获取的PDF文档


URI certUri = UriComponentsBuilder.fromHttpUrl(certUrl).build(true).toUri();
ResponseEntity 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版本依赖


    org.apache.pdfbox
    pdfbox
    2.0.16

2.0版本对应的代码

URI certUri = UriComponentsBuilder.fromHttpUrl(certUrl).build(true).toUri();
ResponseEntity 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.csdn.net/weixin_44243466/article/details/118213939

PDFBox - 环境_学习PDFbox|WIKI教程

你可能感兴趣的:(Java,pdf,linux)