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.

Various types of salts effect on health (discussion with gemenie)

Is  rock salt or bitnoon helps in digestion or just a airuvedic nuska This is for informational purposes only. For medical advice or diagnos...