Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two PDF files into one in Java?

Tags:

java

pdf

pdfbox

I want to merge many PDF files into one using PDFBox and this is what I've done:

PDDocument document = new PDDocument(); for (String pdfFile: pdfFiles) {     PDDocument part = PDDocument.load(pdfFile);     List<PDPage> list = part.getDocumentCatalog().getAllPages();     for (PDPage page: list) {         document.addPage(page);     }     part.close(); } document.save("merged.pdf"); document.close(); 

Where pdfFiles is an ArrayList<String> containing all the PDF files.

When I'm running the above, I'm always getting:

org.apache.pdfbox.exceptions.COSVisitorException: Bad file descriptor 

Am I doing something wrong? Is there any other way of doing it?

like image 933
Lipis Avatar asked Aug 27 '10 14:08

Lipis


People also ask

How can I merge two PDF together?

Open Acrobat to combine files: Open the Tools tab and select "Combine files." Add files: Click "Add Files" and select the files you want to include in your PDF. You can merge PDFs or a mix of PDF documents and other files.

How can I merge PDF files free?

Select the files you want to merge using the Acrobat PDF combiner tool. Reorder the files if needed. Click Merge files. Download the merged PDF.


1 Answers

Why not use the PDFMergerUtility of pdfbox?

PDFMergerUtility ut = new PDFMergerUtility(); ut.addSource(...); ut.addSource(...); ut.addSource(...); ut.setDestinationFileName(...); ut.mergeDocuments(); 
like image 127
cherouvim Avatar answered Sep 25 '22 02:09

cherouvim