思路:base64 -> multipartFile - > pdf
base64 -> multipartFile
/**
* 将 图片base64 - > MultipartFile
* @param base64
* @return
*/
public static MultipartFile base64MultipartFile(String base64) {
try {
String[] baseStr = base64.split(",");
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] b;
b = base64Decoder.decodeBuffer(baseStr[1]);
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;
}
}
multipartFile - > pdf
/**
* 将图片转换为PDF文件
*
* @param file SpringMVC获取的图片文件
* @return PDF文件
* @throws IOException IO异常
* @throws DocumentException PDF文档异常
*/
private static File generatePdfFile(MultipartFile file) throws IOException, DocumentException {
String fileName = file.getOriginalFilename();
String pdfFileName;
if (fileName != null) {
pdfFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";
} else {
return null;
}
Document doc = new Document(PageSize.A4, 100, 100, 20, 30);
PdfWriter.getInstance(doc, new FileOutputStream(pdfFileName));
doc.open();
doc.newPage();
Image image = Image.getInstance(file.getBytes());
float height = image.getHeight();
float width = image.getWidth();
int percent = getPercent(height, width);
image.setAlignment(Image.MIDDLE);
image.scalePercent(percent);
doc.add(image);
doc.close();
return new File(pdfFileName);
}
/**
* 等比压缩,获取压缩百分比
* @param height 图片的高度
* @param weight 图片的宽度
* @return 压缩百分比
*/
private static int getPercent(float height, float weight) {
float percent;
if (height > weight) {
percent = PageSize.A4.getHeight() / height * 100;
} else {
percent = PageSize.A4.getWidth() / weight * 100;
}
// -5 多缩放一点 不影响内容
percent -= 5;
return Math.round(percent);
}
如果还需要转成multipartFile方便调用api上传的话
pdf file - > multipartFile
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFilePDF = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
pom 依赖 itextpdf
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>