private static void convertImagesToPdf(ArrayList<String> imagesFilePath, String pdfFilePath) throws Exception {
try ( PDDocument doc = new PDDocument();) {
for (String imageFilePath : imagesFilePath) {
PDImageXObject image = PDImageXObject.createFromFile(imageFilePath, doc);
PDRectangle pageSize = PDRectangle.A4;
int originalWidth = image.getWidth();
int originalHeight = image.getHeight();
float pageWidth = pageSize.getWidth();
float pageHeight = pageSize.getHeight();
float ratio = Math.min(pageWidth / originalWidth, pageHeight / originalHeight);
float scaledWidth = originalWidth * ratio;
float scaledHeight = originalHeight * ratio;
float x = (pageWidth - scaledWidth) / 2;
float y = (pageHeight - scaledHeight) / 2;
PDPage page = new PDPage(pageSize);
doc.addPage(page);
try ( PDPageContentStream contents = new PDPageContentStream(doc, page)) {
contents.drawImage(image, x, y, scaledWidth, scaledHeight);
}
}
doc.save(pdfFilePath);
}
}
Comments
Post a Comment
If you have any doubts, please let me know.