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

图片转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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章