当前位置: 首页 > 工具软件 > PDFBox > 使用案例 >

PDFBox实现图片转PDF --JAVA

子车凯泽
2023-12-01
  • maven依赖
	<dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox-app</artifactId>
        <version>2.0.19</version>
    </dependency>
  • 代码实现
public class ImgSynthesisPdfUtils {
    /**
     * 多图片合成pdf的限制后缀
     */
    private static final List IMAGE_SUFFIX = Arrays.asList("jpg", "png", "jpeg");
    /**
     * 多个图片合成一个pdf
     *
     * @param imgFolder 多图片的文件夹路径  例如:"D:\\image\\"
     * @param target    合并的图片路径          "D:\\image\\merge.pdf"
     * @throws IOException
     */
    public static void manyImageToOnePdf(String imgFolder, String target) throws IOException {
        PDDocument doc = new PDDocument();
        //创建一个空的pdf文件
        doc.save(target);

        PDPage page;
        PDImageXObject pdImage;
        PDPageContentStream contents;
        BufferedImage bufferedImage;
        String fileName;
        float w, h;
        String suffix;
        File tempFile;
        int index;

        File folder = new File(imgFolder);
        for (int i = 0; i < folder.listFiles().length; i++) {
            tempFile = folder.listFiles()[i];
            if (!tempFile.isFile()) {
                continue;
            }

            fileName = tempFile.getName();
            index = fileName.lastIndexOf(".");
            if (index == -1) {
                continue;
            }
            //获取文件的后缀
            suffix = fileName.substring(index + 1);
            //如果文件后缀不是图片格式,跳过当前循环
            if (!IMAGE_SUFFIX.contains(suffix)) {
                continue;
            }

            bufferedImage = ImageIO.read(folder.listFiles()[i]);
            //Retrieving the page
            pdImage = LosslessFactory.createFromImage(doc, bufferedImage);
            w = pdImage.getWidth();
            h = pdImage.getHeight();
            page = new PDPage(new PDRectangle(w, h));
            contents = new PDPageContentStream(doc, page);
            contents.drawImage(pdImage, 0, 0, w/2, h/2);
            System.out.println("Image inserted");
            contents.close();
            doc.addPage(page);
        }
        //保存pdf
        doc.save(target);
        //关闭pdf
        doc.close();
    }
}
  • 补充
    使用pdfBox实现图片转pdf效率会比较慢,合成的pdf文件会比较大。
 类似资料: