Merge 2 PDFs in Java

2019-02-21 06:20发布

问题:

I have a Problem with iText and merging of 2PDFs to 1 PDF.

I would like to merge this PDFs:

PDF1 - One Site:

This is PDF1.

PDF2 - One Site:

This is PDF2.

What I need: https://dl.dropboxusercontent.com/u/4001370/whatIneed.pdf

Code 1 - Two Sites:

One Site One: This is PDF1.
One Site Two: This is PDF2.

    PDFMergerUtility ut = new PDFMergerUtility();
    ut.addSource("C:\\Temp\\PDF1.pdf");
    ut.addSource("C:\\Temp\\PDF2.pdf");
    ut.setDestinationFileName("C:\\Temp\\Code1.pdf");
    ut.mergeDocuments();

Code 2 - The number is overwritten:

This is PDF(1/2).

public class main {
public static void main(String[] args) throws IOException, DocumentException {
    PdfReader reader;
    PdfImportedPage page;


    LinkedList<File> fileList = new LinkedList<File>();
    fileList.add(new File("C:\\Temp\\PDF1.pdf"));
    fileList.add(new File("C:\\Temp\\PDF2.pdf"));


    File ergebnis = new File("C:\\Temp\\Code2.pdf");
    Document document2 = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.getInstance(document2, new FileOutputStream(ergebnis));

    document2.open();
    PdfContentByte canvas = writer.getDirectContent();

    // Header 
    reader = new PdfReader(fileList.get(0).getAbsolutePath());
    page = writer.getImportedPage(reader, 1);
    canvas.addTemplate(page, 0, 0);
    // Aufgabe
    reader = new PdfReader(fileList.get(1).getAbsolutePath());
    for(int i=1; i<=reader.getNumberOfPages(); i++){
        page = writer.getImportedPage(reader, i);
        canvas.addTemplate(page, 0, 0);
        document2.newPage();
    }

    document2.close();
    writer.close();
}

}

I have no Idea. I hope you can help me at this problem.

回答1:

Please read Chapter 6 of my book. It explains why using PdfWriter/PdfImportedPage is the wrong way to merge documents. You should use PdfCopy or PdfSmartCopy if you want to concatenate two documents. You should use PdfStamper if you want one document to act as company stationery for the other document. From your question, it's not clear which one of both you need (you leave that open to interpretation), so please read chapter 6. I've done the effort of writing it and making available for free so that you can choose the solution that is right for you.



回答2:

The question is a bit vague - if you are asking how to take two PDFs and merge them together, this SO article shows the easiest way to do it in iText: How to merge different documents into single one?



标签: java pdf itext