<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ImageToPDF {
public static void main(String[] arg){
//创建个存放图片地址的集合
List<String> imageUrlList = new ArrayList();
//添加图片地址到集合
imageUrlList.add("/Users/mac/Desktop/WechatIMG18.png");
//存放pdf文件的路径
String pdfUrl = "/Users/mac/Desktop/123.pdf";
imgOfPdf(imageUrlList,pdfUrl);
}
public static void imgOfPdf(List<String> imageUrlList,String pdfUrl) {
try {
File file = PdfUtilImg(imageUrlList, pdfUrl);//生成pdf
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
public static File PdfUtilImg(List<String> imageUrllist, String pdfUrl) {
//new一个pdf文档
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
try {
//pdf写入
PdfWriter.getInstance(doc, new FileOutputStream(pdfUrl));
//打开文档
doc.open();
//遍历集合,将图片放在pdf文件
for (int i = 0; i < imageUrllist.size(); i++) {
//在pdf创建一页 主:此处为每一张图片是pdf文件的一页
doc.newPage();
//通过文件路径获取image
Image png1 = Image.getInstance(imageUrllist.get(i));
float heigth = png1.getHeight();
float width = png1.getWidth();
int percent = getPercent2(heigth, width);
png1.setAlignment(Image.MIDDLE);
// 表示是原来图像的比例;
png1.scalePercent(percent+3);
doc.add(png1);
}
doc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//输出流
File mOutputPdfFile = new File(pdfUrl);
if (!mOutputPdfFile.exists()) {
mOutputPdfFile.deleteOnExit();
return null;
}
//反回文件输出流
return mOutputPdfFile;
}
public static int getPercent(float h, float w) {
int p = 0;
float p2 = 0.0f;
if (h > w) {
p2 = 297 / h * 100;
} else {
p2 = 210 / w * 100;
}
p = Math.round(p2);
return p;
}
public static int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
}