PDF技术(三)-Java实现图片转PDF文件

版权声明:本文为博主原创文章,转载添加原文链接 https://blog.csdn.net/qq_34190023/article/details/82999608

图片转pdf文件同样采用itext,将图片加入即可

1)使用IText转换

原理:

使用IText创建pdf,添加图片。

优点:

速度快。

具体实现

public class Image2PDF {
    /*** @param picturePath 图片地址*/
    private static void createPic(Document document,String picturePath) {
        try {
            Image image = Image.getInstance(picturePath);
            float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
            float documentHeight = documentWidth / 580 * 320;//重新设置宽高
            image.scaleAbsolute(documentWidth, documentHeight);//重新设置宽高
            document.add(image);
        } catch (Exception ex) {
        }
    }
    public static void image2pdf(String text, String pdf) throws DocumentException, IOException {
        Document document = new Document();
        OutputStream os = new FileOutputStream(new File(pdf));
        PdfWriter.getInstance(document,os);
        document.open();
        createPic(document,text);
        document.close();
    }
    public static void main(String[] args) throws IOException, DocumentException {
        image2pdf("F:\\pdf\\img\\不老梦.jpg","F:\\pdf\\213123.pdf");
    }
}

效率分析

耗时:801ms

耗时:778ms

耗时:742ms

耗时:789ms

耗时:777ms

猜你喜欢

转载自blog.csdn.net/qq_34190023/article/details/82999608