Java实现PDF转图片

628 阅读1分钟

PDFBox:PDFBox是Java实现的PDF文档协作类库,提供PDF文档的创建、处理以及文档内容提取功能,也包含了一些命令行实用工具。

  • 引入PDFBox依赖(Maven)
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.28</version>
</dependency>
  • PDF转图片工具类
public class PDFUtils {

    // 参数越高,转换成图片的清晰度越高。1 SCALE = 72 DPI
    public static final float SCALE = 3;

    public static final String IMG_TYPE = "png";

    public static final String DOT = ".";

    /**
     * PDF转图片
     *
     * @param pdfFilePath
     * @throws IOException
     */
    public static void pdfToImg(String pdfFilePath) throws IOException {
        // 打开PDF文档
        PDDocument document = PDDocument.load(new File(pdfFilePath));
        // 生成PDF Renderer
        PDFRenderer renderer = new PDFRenderer(document);
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            // 根据页面数,逐页渲染
            BufferedImage image = renderer.renderImage(i, SCALE);
            // 生成图片文件名
            String fileName = (i + 1) + DOT + IMG_TYPE;
            File imageFile = new File(fileName);
            // 写入文件
            ImageIO.write(image, IMG_TYPE, imageFile);
        }
        document.close();
    }
}