java – PdfBox 图片转pdf

  • Post author:
  • Post category:java


/**
     * 图片转pdf(A4大小,图片等比缩放[可能会导致模糊],居中展示)
     * @param outPdfFilepath 生成pdf文件路径
     * @param imgFiles 需要转换的图片File类Array,按array的顺序合成图片
     */
    public static void imgsToPdfA4(String outPdfFilepath, File[] imgFiles) throws Exception {
        PDDocument document = new PDDocument();
        logger.info(">>>>>>>>>>>>>> 图片合成PDF <<<<<<<<<<<<<< ");

        for (File imgFile : imgFiles) {
            String imgName = imgFile.getName().toLowerCase();
            if (imgName.endsWith(".bmp")
                || imgName.endsWith(".jpg")
                || imgName.endsWith(".jpeg")
                || imgName.endsWith(".gif")
                || imgName.endsWith(".png"))
            {
                InputStream in = new FileInputStream(imgFile);

                BufferedImage bimg = ImageIO.read(in);
                int width = bimg.getWidth();
                int height = bimg.getHeight();

                PDPage page = new PDPage(PDRectangle.A4);
                document.addPage(page);

                PDImageXObject pdImage = PDImageXObject.createFromFileByExtension(imgFile, document);

                float scale = 1f;

                float s1 = PDRectangle.A4.getWidth() / width;
                float s2 = PDRectangle.A4.getHeight() / height;

                float resWidth = width;
                float resHeight = height;

                if(s1 < 1 || s2 < 1) {
                    if (s1 > s2){
                        scale = s2;
                    } else {
                        scale = s1;
                    }
                    resHeight = height * scale;
                    resWidth = width * scale;
                }

                float x = (PDRectangle.A4.getWidth() - resWidth)/2;
                float y = (PDRectangle.A4.getHeight() - resHeight)/2;

                logger.info("添加图片 {} 原图 w:{} h:{}, scale w:{} h:{}",imgFile.getPath(),width,height,resWidth,resHeight);

                PDPageContentStream contentStream = new PDPageContentStream(document, page);
                contentStream.drawImage(pdImage, x, y, resWidth,resHeight);
                contentStream.close();

            }else{
                logger.info("不支持该文件[略过],{}",imgFile.getPath());
            }
        }
        document.save(outPdfFilepath);
        document.close();
        logger.info(">>>>>>>>>>>>>> 图片合成PDF完成 <<<<<<<<<<<<<<");
    }
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.15</version>
        </dependency>



版权声明:本文为qq_33234268原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。