pdf页转图片

发布时间 2023-04-04 15:18:06作者: 橙香五花肉

pdf转图片

依赖

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>fontbox</artifactId>
    <version>2.0.24</version>
</dependency>

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

代码

/**
 * pdf转图片 目前只转第一页
 * 
 * @param pdfPath pdf文件路径
 * @param outPath 转为图片的输出路径
 */
public static void pdfToImg(String pdfPath, String outPath){

    PDDocument doc = null;
    try {
        doc = PDDocument.load(new File(pdfPath));
        PDFRenderer renderer = new PDFRenderer(doc);
        // 0:转pdf第一页
        BufferedImage image = renderer.renderImageWithDPI(0, 144);

        ImageIO.write(image, "png", new File(outPath));

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (null != doc) {
                doc.close();
            }
        } catch (Exception ignored) {}
    }
}