在Java代码中使用pdfBox将PDF转换为图片

生成图片

            // 生成图片
            PDDocument pd = PDDocument.load(new File(filePath));
            PDFRenderer pdfRenderer = new PDFRenderer(pd);
            BufferedImage combined = null;
            for (int page = 0; page < pd.getNumberOfPages(); ++page)
            {
                BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 96, ImageType.RGB);
                if (page == 0) {
                    combined = bim;
                } else {
                    combined = merge(combined, bim);
                }
            }
            ImageIOUtil.writeImage(combined, filePath + ".png", 96);
            pd.close();

合并图片的工具方法

    private static BufferedImage merge(BufferedImage image1, BufferedImage image2) {
        BufferedImage combined = new BufferedImage(
                image1.getWidth(),
                image1.getHeight() + image2.getHeight(),
                BufferedImage.TYPE_INT_RGB);

        Graphics g = combined.getGraphics();
        g.drawImage(image1, 0, 0, null);
        g.drawImage(image2, 0, image1.getHeight(), null);
        g.dispose();
        return combined;
    }

 

你可能感兴趣的:(在Java代码中使用pdfBox将PDF转换为图片)