public File ImageToPdf(MultipartFile file) throws IOException, DocumentException {
String fileName = file.getOriginalFilename();
String pdfFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
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();
File pdfFile = new File(pdfFileName);
return pdfFile;
}
/**
* @Description: 等比压缩,获取压缩百分比
* @param height 图片的高度
* @param weight 图片的宽度
* @return 压缩百分比
*/
private static int getPercent(float height, float weight) {
float percent = 0.0F;
if (height > weight) {
percent = PageSize.A4.getHeight() / height * 100;
} else {
percent = PageSize.A4.getWidth() / weight * 100;
}
return Math.round(percent);
}
MultipartFile 格式图片转pdf
于 2023-07-05 10:15:56 首次发布