PDF转图片

依赖如下:

1
2
3
4
5
6
7

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.20</version>
</dependency>

我的代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21

public static List<byte[]> transferPdfToPictures(InputStream inputStream) {
    try (PDDocument document = PDDocument.load(inputStream)) {

        List<byte[]> result = new ArrayList<>();

        PDFRenderer renderer = new PDFRenderer(document);
        for (int i = 0; i < document.getNumberOfPages(); ++i) {
            BufferedImage bufferedImage = renderer.renderImageWithDPI(i, DPI);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, IMG_TYPE, out);
            result.add(out.toByteArray());
        }

        return result;
    } catch (Exception e) {
        e.printStackTrace();
        throw new BusinessException(PDF_TRANSFER_WRONG);
    }
}

参考资料

  1. Java实现PDF转图片