最近接到一个需求,要求多张图片合并成一个PDF并且以Base64当出入参,来直接上干货。
需要用到的包:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.2</version>
</dependency>
<!-- hutool测试用 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.5</version>
</dependency>
代码:
/**
* 图片转pdf
* @param imgStrList 图片base64
* @param target
*/
public static String ImgChangePDF(List<String> imgStrList, String target) {
String result = "";
//创建一个文档对象
Document doc = new Document();
try {
//定义输出文件的位置
PdfWriter.getInstance(doc, new FileOutputStream(target));
//开启文档
doc.open();
// 循环获取图片文件夹内的图片
for (String imgStr : imgStrList) {
if(imgStr == null) {
continue;
}
//路径
MultipartFile multipartFile = base64MultipartFile(imgStr);
Image img = Image.getInstance(multipartFile.getBytes());
//获得宽高
Float h = img.getHeight();
Float w = img.getWidth();
//统一压缩
Integer percent = getPercent(h, w);
//图片居中
img.setAlignment(Image.MIDDLE);
//百分比显示图
img.scalePercent(percent);
//设置高和宽的比例
doc.add(img);
}
// 关闭文档
if(doc != null){
doc.close();
}
//转Base64
File pdfFile = new File(target);
FileInputStream fileInputStream = new FileInputStream(pdfFile);
byte[] byteBuff = new byte[(int) pdfFile.length()];
fileInputStream.read(byteBuff);
fileInputStream.close();
result = new BASE64Encoder().encode(byteBuff);
if(pdfFile!=null){
pdfFile.delete();
}
} catch (IOException e) {
e.printStackTrace();
} catch (BadElementException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
return result;
}
/**
* 压缩
* @param h
* @param w
* @return
*/
public static Integer getPercent(Float h,Float w) {
Integer g = 0;
Float g2 = 0.0f;
g2 = 480 / w * 100;
g = Math.round(g2);
return g;
}
public static MultipartFile base64MultipartFile(String base64) {
try {
String[] baseStr = base64.split(",");
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] b;
b = base64Decoder.decodeBuffer(baseStr[0]);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64DecodedMultipartFile(b, baseStr[0]);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) throws Exception{
List<String> source = new ArrayList<String>();
//这里我把图片base64存txt里面了,具体你们自己改
source.add(new cn.hutool.core.io.file.FileReader("F://1.txt").readString());
source.add(new cn.hutool.core.io.file.FileReader("F://2.txt").readString());
String str = ImgChangePDF(source, IdUtil.simpleUUID()+".pdf");
System.out.println(str);
}