加入itext的依賴
<!--图片转pdf-->
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
封装转换的工具类
/*
图片转成pdf工具类
*/
public class ImageToPdfUtils {
/**
* imageUrllist:图片路径集合,
* mOutputPdfFileName:pdf输出位置
* @param imageUrllist
* @param mOutputPdfFileName
* @return
*/
public static File imageToPdf(List<String> imageUrllist, String mOutputPdfFileName) {
String TAG = "PdfManager";
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
//导出的pdf名称,这里使用的是IdWorker
Long aLong = IdWorkerUtils.generateId();
try {
PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName+"\\"+aLong+".pdf"));
doc.open();
for (int i = 0; i < imageUrllist.size(); i++) {
doc.newPage();
// doc.add(new Paragraph("简单使用iText"));
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);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
doc.close();
}
File mOutputPdfFile = new File(mOutputPdfFileName);
if (!mOutputPdfFile.exists()) {
mOutputPdfFile.deleteOnExit();
return null;
}
return mOutputPdfFile;
}
/**
* 第一种解决方案 在不改变图片形状的同时,判断,如果h>w,则按h压缩,否则在w>h或w=h的情况下,按宽度压缩
*
* @param h
* @param w
* @return
*/
private 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;
}
/**
* 第二种解决方案,统一按照宽度压缩 这样来的效果是,所有图片的宽度是相等的(推荐)
*
* @param
*/
private static int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
接下来调用即可