导包
<dependency>
<groupId>org.eclipse.birt.runtime.3_7_1</groupId>
<artifactId>com.lowagie.text</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.7</version>
</dependency>
编写工具类
package com.study;
import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
public class ImageToPDF {
public static void toPdf(String imageFolderPath, String pdfPath) {
try {
String imagePath = null;
FileOutputStream fos = new FileOutputStream(pdfPath);
Document doc = new Document(null, 0, 0, 0, 0);
PdfWriter.getInstance(doc, fos);
BufferedImage img = null;
Image image = null;
File file = new File(imageFolderPath);
File[] files = file.listFiles();
for (File file1 : files) {
if (file1.getName().endsWith(".png") || file1.getName().endsWith(".jpg") || file1.getName().endsWith(".gif")
|| file1.getName().endsWith(".jpeg") || file1.getName().endsWith(".tif")) {
imagePath = imageFolderPath + file1.getName();
System.out.println(file1.getName());
img = ImageIO.read(new File(imagePath));
doc.setPageSize(new Rectangle(img.getWidth(), img
.getHeight()));
doc.setPageSize(new Rectangle(img.getWidth(), img
.getHeight()));
image = Image.getInstance(imagePath);
doc.open();
doc.add(image);
}
}
doc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试使用
public static void main(String[] args) {
long time1 = System.currentTimeMillis();
toPdf("E:\\image\\", "E:\\hebing.pdf");
long time2 = System.currentTimeMillis();
int time = (int) ((time2 - time1) / 1000);
System.out.println("执行了:" + time + "秒!");
}