图片转pdf

本文介绍了一种将图片文件(如jpg, png等)转换为PDF格式的方法,通过使用Java编程语言实现。文章详细解释了如何创建PDF文档,设置页面大小,加载图片,并调整图片尺寸以适应A4纸张大小,确保图片在转换后的PDF中居中显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 图片转换pdf(jpg,png等)
 * @param filePath
 * @param pdfPath
 * @throws IOException
 */
public static boolean Image2PDF(String filePath, String pdfPath) throws IOException {
    boolean bool=true;
    File file = new File(filePath);
    if (file.exists()) {
        Document document = new Document();

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(pdfPath);
            PdfWriter.getInstance(document, fos);
            document.setPageSize(PageSize.A4);
            document.open();
            Image image = Image.getInstance(filePath);
            float imageHeight = image.getScaledHeight();
            float imageWidth = image.getScaledWidth();
            image.setAlignment(Image.ALIGN_CENTER);
            int percent = getPercent(imageHeight, imageWidth);
            image.scalePercent(percent);
            document.add(image);
        } catch (DocumentException de) {
            System.out.println(de.getMessage());
            bool=false;
            return bool;
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
            bool=false;
            return bool;
        }
        document.close();
        fos.flush();
        fos.close();
    }
    bool=false;
    return bool;
}

 

/**
 * 图片倍率大小 a4
 * @param h
 * @param w
 * @return
 */
public static int getPercent(float h, float w) {
    int p = 0;
    float p2 = 0.0f;
    if (h > w) {
        p2 = 297 / h * 274;
    } else {
        p2 = 210 / w * 268;
    }
    p = Math.round(p2);
    return p;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值