java 图片合并成pdf_Java多张图片合成PDF

该博客介绍了如何使用Java的iText库将多张图片合并成一个PDF文件。通过Img2PdfUtil工具类,实现了读取指定路径的图片,然后按照特定顺序将这些图片添加到PDF文档中,并调整图片大小以适应页面。最后,关闭文档,完成图片到PDF的转换过程。
摘要由CSDN通过智能技术生成

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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值