【将图片链接中的图片合并成PDF】

将图片链接中的图片合并成PDF

1.需要使用到pdfbox

老规矩,加依赖先

        <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.25</version>
        </dependency>
2.上代码
    /**
     * 单个图片合并成PDF
     *
     * @param pdDocument pdf文档对象
     * @param imageUrl 图片的url
     */
    public static PDDocument mergeImageToPdf(PDDocument pdDocument, String imageUrl) throws IOException {
        //从url加载图像到内存
        BufferedImage image = ImageIO.read(new URL(imageUrl));
        //创建页面
        PDPage page = new PDPage(PDRectangle.A4);
        pdDocument.addPage(page);
        //创建内容流
        try (PDPageContentStream pdPageContentStream = new PDPageContentStream(pdDocument, page)){
            float imageWidth = page.getMediaBox().getWidth();
            float imageHeight = page.getMediaBox().getHeight();

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", byteArrayOutputStream);
            byte[] result= byteArrayOutputStream.toByteArray();

            //将内存中的图像添加到页面内容流中
            PDImageXObject pdImageXObject = PDImageXObject.createFromByteArray(pdDocument, result, null);
            // 确保图片按比例缩放以适合页面大小
            float scale = Math.min(imageWidth / image.getWidth(), imageHeight / image.getHeight());
            //添加到PDF上
            pdPageContentStream.drawImage(pdImageXObject, 0, 0, image.getWidth()* scale, image.getHeight() * scale);

//          pdPageContentStream.close();//在try中任务结束后会释放资源
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pdDocument;
    }
    /**
     * N图片合并
     *
     * @param imageUrls
     * @return
     */
    public static PDDocument imageToPdfMerger(List<String> imageUrls) {

        //创建新的PDF文档
        PDDocument pdDocument = new PDDocument(MemoryUsageSetting.setupMainMemoryOnly());
        //创建线程池
        //ExecutorService executor = Executors.newFixedThreadPool(imageUrls.length);
        for (String imageUrl : imageUrls) {
            try {
                mergeImageToPdf(pdDocument, imageUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return pdDocument;
    }
3.如果需要保存至本地则直接 pdDocument.save(“文件名称”)
4.如果需要上传到某个文件系统,可转化为字节流进行操作
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值