importcom.itextpdf.text.Document;importcom.itextpdf.text.Image;importcom.itextpdf.text.Rectangle;importcom.itextpdf.text.pdf.PdfWriter;importjava.io.File;importjava.io.FileOutputStream;importorg.apache.log4j.Logger;/*** 图片转pdf工具类
*
*@authorAdministrator
**/
public classImg2PdfUtil {private static Logger logger = Logger.getLogger(Img2PdfUtil.class);/***
*@paramoutPdfFilepath 生成pdf文件路径
*@paramimageFiles 需要转换的图片File类Array,按array的顺序合成图片*/
public static void imagesToPdf(String outPdfFilepath, File[] imageFiles) throwsException {
logger.info("进入图片合成PDF工具方法");
File file= newFile(outPdfFilepath);//第一步:创建一个document对象。
Document document = newDocument();
document.setMargins(0, 0, 0, 0);//第二步://创建一个PdfWriter实例,
PdfWriter.getInstance(document, newFileOutputStream(file));//第三步:打开文档。
document.open();//第四步:在文档中增加图片。
int len =imageFiles.length;for (int i = 0; i < len; i++) {if (imageFiles[i].getName().toLowerCase().endsWith(".bmp")|| imageFiles[i].getName().toLowerCase().endsWith(".jpg")|| imageFiles[i].getName().toLowerCase().endsWith(".jpeg")|| imageFiles[i].getName().toLowerCase().endsWith(".gif")|| imageFiles[i].getName().toLowerCase().endsWith(".png")) {
String temp=imageFiles[i].getAbsolutePath();
logger.info("图片路径:"+temp);
Image img=Image.getInstance(temp);
img.setAlignment(Image.ALIGN_CENTER);
img.scaleAbsolute(597, 844);//直接设定显示尺寸//根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效//document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
document.setPageSize(new Rectangle(597, 844));
document.newPage();
document.add(img);
}
}//第五步:关闭文档。
document.close();
logger.info("图片合成PDF完成");
}public static voidmain(String[] args) {
String outPdfPath= "C:\\Users\\Administrator\\Desktop\\广东\\需求\\20190104已确认需求\\Img2PdfTest\\Img2pdf.pdf";
String imagesPath= "C:\\Users\\Administrator\\Desktop\\广东\\需求\\20190104已确认需求\\Img2PdfTest";
String[] imgNameArray= new String[] { "1_0.png", "1_1.png", "1_2.png", "1_3.png", "1_4.png", "1_5.png","1_6.png", "1_7.png", "1_8.png", "1_9.png", "1_10.png", "1_11.png", };//imagesToPdf(outPdfPath, imagesPath, imgNameArray);
}
}