public static File generatePdfFile(File imageFile) throws Exception {
String fileName = imageFile.getName();
String pdfFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";
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);
}
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);
}
private static float mmToPoints(float mm) {
return mm * 2.83465f;
}