跳到主要内容

使用itextpdf将图片转pdf

依赖

<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>

实现代码

/**
* 将图片转换为PDF文件
* @param imageFile 图片文件
*/
public static File generatePdfFile(File imageFile) throws Exception {
String fileName = imageFile.getName();
String pdfFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";
//纸张大小A4
// Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
//纸张大小7寸,100 × 150 毫米(纵向)
float mm100Width = mmToPoints(100);
float mm150Height = mmToPoints(150);
RectangleReadOnly rectangleReadOnly = new RectangleReadOnly(mm100Width, mm150Height);
Document doc = new Document(rectangleReadOnly, 0, 0, 0, 0);
PdfWriter.getInstance(doc, Files.newOutputStream(Paths.get(pdfFileName)));
doc.open();
doc.newPage();
Image image = Image.getInstance(Files.readAllBytes(imageFile.toPath()));
float height = image.getHeight();
float width = image.getWidth();
int percent = getPercent(rectangleReadOnly, 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(RectangleReadOnly rectangleReadOnly, float height, float weight) {
float percent = 0.0F;
if (height > weight) {
percent = rectangleReadOnly.getHeight() / height * 100;
} else {
percent = rectangleReadOnly.getWidth() / weight * 100;
}
return Math.round(percent);
}


/**
* 将毫米转换为点
* @param mm 尺寸大小,单位毫米 (1 mm = 2.83465 points)
*/
private static float mmToPoints(float mm) {
return mm * 2.83465f;
}