iText - how to add pages to a document created with PdfCopy

冷暖自知 提交于 2019-12-05 04:17:02

I recently had this issue, and the answers here arent actually that helpful. My use-case was basically "Take a bunch of PDFs and images (.jpg, .png etc) and combine them all into 1 PDF". I had to use PdfCopy because it preserves things like form fields and labels, where PdfWriter doesnt.

Basically, because PdfCopy wont allow you to create new pages with addPage(), you have to create a new PDF in memory with the image on the page, and then use PdfCopy to copy out the page from that PDF.

For example:

    Document pdfDocument = new Document();
    ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
    PdfCopy copy = new PdfCopy(pdfDocument, pdfOutputStream);

    pdfDocument.open();

    for (File file : allFiles) {
       if (/* file is PDF */) {
           /* Copy all the pages in the PDF file into the new PDF */
           PdfReader reader = new PdfReader(file.getAllBytes());
           for (int i = 1; i <= reader.getNumberOfPages(); i++) {
              copy.addPage(copy.getImportedPage(reader, i);
           }
       } else {
           /* File is image. Create a new PDF in memory, write the image to its first page, and then use PdfCopy to copy that first page back into the main PDF */
           Document imageDocument = new Document();
           ByteArrayOutputStream imageDocumentOutputStream = new ByteArrayOutputStream();
           PdfWriter imageDocumentWriter = PdfWriter.getInstance(imageDocument, imageDocumentOutputStream);

            imageDocument.open();

            if (imageDocument.newPage()) {

                image = Image.getInstance(file.getAllBytes());

                if (!imageDocument.add(image)) {
                   throw new Exception("Unable to add image to page!");
                }

                imageDocument.close();
                imageDocumentWriter.close();

                PdfReader imageDocumentReader = new PdfReader(imageDocumentOutputStream.toByteArray());

                copy.addPage(copy.getImportedPage(imageDocumentReader, 1));

                imageDocumentReader.close();
         }

     }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!