Java实现将图片转换成PDF

1.引入依赖

<dependency>
   <groupId>org.apache.pdfbox</groupId>
   <artifactId>pdfbox</artifactId>
   <version>2.0.24</version>
</dependency>

2.工具方法

package com.prescription.transfer.system.utils;

import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ImgToPdf {

    /**
     * 图片转Pdf
     *
     * @param imgFile
     * @return
     * @throws IOException
     */
    public static File getPdfFile(File imgFile, String filePath) throws IOException {
        File outputFile = new File(filePath);
        genPdf(readBytesFromFile(imgFile), outputFile);
        return outputFile;
    }

    private static void genPdf(byte[] imageBytes, File outputFile) throws IOException {
        PDDocument document = new PDDocument();
        //2. 生成一页 PDF document
        PDImageXObject image = PDImageXObject.createFromByteArray(document, imageBytes, "image");
        // 这里是你生成PDF自适应图片大小,不设置会默认为A4
        PDRectangle pageSize = new PDRectangle(image.getWidth(), image.getHeight());
        PDPage page = new PDPage(pageSize);

        document.addPage(page);
        // 3.将 图片 添加进PDF document
        PDPageContentStream contentStream = new PDPageContentStream(document, page);
        float pageWidth = pageSize.getWidth();
        float pageHeight = pageSize.getHeight();
        float imageWidth = image.getWidth();
        float imageHeight = image.getHeight();
        float scale = Math.min(pageWidth / imageWidth, pageHeight / imageHeight);
        float scaledWidth = imageWidth * scale;
        float scaledHeight = imageHeight * scale;
        float x = (pageWidth - scaledWidth) / 2;
        float y = (pageHeight - scaledHeight) / 2;
        // 这里是将你的图片填充入pdf页
        contentStream.drawImage(image, x, y, scaledWidth, scaledHeight);
        contentStream.close();
        document.save(outputFile);
        document.close();
    }

    /**
     * 从文件读取字节
     *
     * @param file 文件
     * @return {@link byte[]}
     * @throws IOException ioexception
     */
    private static byte[] readBytesFromFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = IOUtils.toByteArray(inputStream);
        inputStream.close();
        return bytes;
    }

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XuDream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值