圖片轉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