Notes: Java module to convert list of images to PDF document using Apache PDFBox

 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);

        }

    }

No comments:

Post a Comment

If you have any doubts, please let me know.

Regarding site Free Browser Tool (https://free-browser-tools.mohitkrgupta.dev) (discussion with google search AI)

Various discussions with Google Search AI regarding site  Free Browser Tool are as below: site free-browser-tools.mohitkrgupta.dev what doe...