简体   繁体   中英

How to append a PDF file to an existing one with iText?

In an application I am trying to append multiple PDF files to a single already existing file. Using iText I found this

Using iText I found this tutorial, which, in my case doesn't seem to work.

Here are some ways I've tried to make it work.

String path = "path/to/destination.pdf";
PdfCopy mergedFile = new PdfCopy(pdf, new FileOutputStream(path));

PdfReader reader;
for(String toMergePath : toMergePaths){
    reader = new PdfReader(toMergePath);
    mergedFile.addDocument(reader);
    mergedFile.freeReader(reader);

    reader.close();
}

mergedFile.close();

When I try to add the document logcat tells me that the document is not open.

But, pdf (the original document) is already open by other methods, and closed only after this one. And, mergedFile is exactly like in the tutorial, which, I believe, must be right.

Did anyone experience the same problem? Otherwise, do anyone know a better method to do what I want to do?

I've seen other solutions copying the bite from one page and append them to a new file but I'm affraid this will "compile" the annotations which I need.

Thank you for your help,

Cordially,

Matthieu Meunier

I hope this code will help you.

public static void mergePdfs(){
     try {
          String[] files = { "D:\\1.pdf" ,"D:\\2.pdf"  ,"D:\\3.pdf" ,"D:\\4.pdf"};
          Document pDFCombineUsingJava = new Document();
          PdfCopy copy = new PdfCopy(pDFCombineUsingJava , new FileOutputStream("D:\\CombinedFile.pdf"));
          pDFCombineUsingJava.open();
          PdfReader ReadInputPDF;
          int number_of_pages;
          for (int i = 0; i < files.length; i++) {
                  ReadInputPDF = new PdfReader(files[i]);
                  copy.addDocument(ReadInputPDF);
                  copy.freeReader(ReadInputPDF);
          }
          pDFCombineUsingJava.close();
        }
        catch (Exception i)
        {
            System.out.println(i);
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM