思路: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>