Java PDF 转图片

引入依赖

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

代码

 

package other;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class Main2 {

    public static void main(String[] args) throws IOException {
        pdf2image();
    }

    public static void pdf2image() throws IOException {
        PDDocument doc = PDDocument.load(new File("123.pdf"));
        int numberOfPages = doc.getNumberOfPages();
        PDFRenderer renderer = new PDFRenderer(doc);
        for (int i = 0; i < numberOfPages; i++) {
            // 页码,从0开始;scale 1 = 72DPI,值越大像素越高;图片类型
            BufferedImage bufferedImage = renderer.renderImage(i, 2, ImageType.RGB);
            String fileName = String.format("123-%d.PNG", i);
            ImageIO.write(bufferedImage, "PNG", new File(fileName));
        }
    }
}

 

PDF:

 

 

输出的图片:

 

 

 

如果报错:

严重: Cannot read JBIG2 image: jbig2-imageio is not installed

引入:

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>jbig2-imageio</artifactId>
    <version>3.0.4</version>
</dependency>

 

posted @ 2022-08-05 11:04  露娜妹  阅读(360)  评论(0编辑  收藏  举报