Search This Blog

Breaking

Saturday, 22 January 2022

January 22, 2022

[Java] [Apache PDFBox] Create new pdf from images and merge PDF's into a single pdf



If we want to create a new pdf with multiple images, then we can do it by using apache pdfbox library.

Here we are trying to create a pdf from an image file first. Later we will merge it for creating a single pdf.

This code is very useful if you are trying to create a report for your pdf comparison, Where you want to show case all your comparison results into a single pdf.



Check the other article on PDF: Create Single page from 3 pages in pdf




public static void main(String[] args) throws IOException {

        String filePath = "Path to \\TestImages\\";

        File folder = new File("Path to \\TestImages\\");

        File[] listOfFiles = folder.listFiles();

        List<File> pdfFileNames = new ArrayList<>();

        List<String> fileNames = new ArrayList<>();

        for (File listOfFile : listOfFiles) {

            fileNames.add(listOfFile.getName());

        }

        System.out.println(fileNames);

        for(String file : fileNames){

          String pdfFile=   createpdfFromFile(file,filePath);

          pdfFileNames.add(new File(pdfFile));

        }

        mergePDF(pdfFileNames,filePath);

    }



private static String getFileNameWithoutExtension(File file) {

        String fileName = "";

        try {

            if (file != null && file.exists()) {

                String name = file.getName();

                fileName = name.replaceFirst("[.][^.]+$", "");

            }

        } catch (Exception e) {

            e.printStackTrace();

            fileName = "";

        }

        return fileName;

    }


private static  void mergePDF(List<File> pdfFileNames, String filepath) throws IOException {

        PDFMergerUtility pdfMerger = new PDFMergerUtility();

        pdfMerger.setDestinationFileName(filepath+ "Report.pdf");

        for(File file: pdfFileNames) {

         pdfMerger.addSource(file);

        }

        pdfMerger.mergeDocuments(null);

        System.out.println("PDF Documents merged to a single file");

    }


    private static String createpdfFromFile(String filename, String filePath) throws IOException {

            String file =  filePath + filename;

            System.out.println(file);

            File fileWithoutExtention = new File(file);

            PDDocument document = new PDDocument();

            InputStream in = new FileInputStream(file);

            BufferedImage bimg = ImageIO.read(in);

            float width = bimg.getWidth();

            float height = bimg.getHeight();

            PDPage page = new PDPage(new PDRectangle(width, height));

            document.addPage(page);

            PDImageXObject pdImage = PDImageXObject.createFromFile(file, document);

            PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true,true);

            contentStream.drawImage(pdImage, 20f, 20f);

            contentStream.close();

            in.close();

            String newPDFFile =filePath + getFileNameWithoutExtension(fileWithoutExtention) + ".pdf";

            document.save(newPDFFile);

            document.close();

            return newPDFFile;

    }