在pom.xml加入如下依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
执行后d盘会生成test.pdf文件 这就是将图片合成后生成的pdf文件
public static void main(String[] args) {
String pdfPath = "d://test.pdf";
List<String> imagePathList = new ArrayList<String>();
imagePathList.add("d://test.jpg");
imagePathList.add("d://test2.jpg");
imagesToPdf(pdfPath,imagePathList);
}
/**
*
* @param pdfFilePath
* 生成pdf文件
* @param imagesPath
* 需要转换的图片路径的数组
*/
public static void imagesToPdf(String pdfFilePath, List<String> imagesPath) {
try {
File file = new File(pdfFilePath);
// 第一步:创建一个document对象。
Document document = new Document();
document.setMargins(0, 0, 0, 0);
// 第二步:
// 创建一个PdfWriter实例,
PdfWriter.getInstance(document, new FileOutputStream(file));
// 第三步:打开文档。
document.open();
// 第四步:在文档中增加图片。
for (String imagePath : imagesPath) {
if (imagePath.toLowerCase().endsWith(".bmp")
|| imagePath.toLowerCase().endsWith(".jpg")
|| imagePath.toLowerCase().endsWith(".jpeg")
|| imagePath.toLowerCase().endsWith(".gif")
|| imagePath.toLowerCase().endsWith(".png")) {
Image img = Image.getInstance(imagePath);
img.setAlignment(Image.ALIGN_CENTER);
// 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
document.newPage();
document.add(img);
}
}
// 第五步:关闭文档。
document.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}