最近接到一个需求,要求多张图片合并成一个PDF并且以Base64当出入参,来直接上干货。
需要用到的包:
<dependency>
<groupId></groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.2</version>
</dependency>
<!-- hutool测试用 -->
<dependency>
<groupId></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 {
//定义输出文件的位置
(doc, new FileOutputStream(target));
//开启文档
();
// 循环获取图片文件夹内的图片
for (String imgStr : imgStrList) {
if(imgStr == null) {
continue;
}
//路径
MultipartFile multipartFile = base64MultipartFile(imgStr);
Image img = (());
//获得宽高
Float h = ();
Float w = ();
//统一压缩
Integer percent = getPercent(h, w);
//图片居中
();
//百分比显示图
(percent);
//设置高和宽的比例
(img);
}
// 关闭文档
if(doc != null){
();
}
//转Base64
File pdfFile = new File(target);
FileInputStream fileInputStream = new FileInputStream(pdfFile);
byte[] byteBuff = new byte[(int) ()];
(byteBuff);
();
result = new BASE64Encoder().encode(byteBuff);
if(pdfFile!=null){
();
}
} catch (IOException e) {
();
} catch (BadElementException e) {
();
} catch (DocumentException e) {
();
}
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 = (g2);
return g;
}
public static MultipartFile base64MultipartFile(String base64) {
try {
String[] baseStr = (",");
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] b;
b = (baseStr[0]);
for (int i = 0; i < ; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64DecodedMultipartFile(b, baseStr[0]);
} catch (Exception e) {
();
return null;
}
}
public static void main(String[] args) throws Exception{
List<String> source = new ArrayList<String>();
//这里我把图片base64存txt里面了,具体你们自己改
(new ("F://").readString());
(new ("F://").readString());
String str = ImgChangePDF(source, ()+".pdf");
(str);
}