Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to merge several pdfs using iText7

Tags:

itext

itext7

I have several datasheets for products. Each is a separate file. What I want to do is to use iText to generate a summary / recommended set of actions, based on answers to a webform, and then append to that all the relevant datasheets. This way, I only need to open one new tab in the browser to print all information, rather than opening one for the summary, and one for each datasheet that is needed.

So, is it possible to do this using iText?

like image 857
Matt Avatar asked Nov 14 '16 13:11

Matt


People also ask

How do you merge multiple PDF files into one?

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 do I combine multiple downloads into one?

Go to File > New Document. Choose the option to Combine Files into a Single PDF. Drag the files that you want to combine into a single PDF into the file-list box. You can add a variety of file types, including PDFs, text files, images, Word, Excel, and PowerPoint documents.

How many PDFs can be combined?

The Acrobat Merge PDFs tool lets you create a merged PDF of up to 1,500 pages. You can combine up to 100 files, with each individual file limited to 500 pages.


1 Answers

Yes, you can merge PDFs using iText 7. E.g. look at the iText 7 Jump-Start tutorial sample C06E04_88th_Oscar_Combine, the pivotal code is:

PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfMerger merger = new PdfMerger(pdf);

//Add pages from the first document
PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
merger.merge(firstSourcePdf, 1, firstSourcePdf.getNumberOfPages());

//Add pages from the second pdf document
PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
merger.merge(secondSourcePdf, 1, secondSourcePdf.getNumberOfPages());

firstSourcePdf.close();
secondSourcePdf.close();
pdf.close();

(C06E04_88th_Oscar_Combine method createPdf)


Depending on your use case, you might want to use the PdfDenseMerger with its helper class PageVerticalAnalyzer instead of the PdfMerger here. It attempts to put content from multiple source pages onto a single target page and corresponds to the iText 5 PdfVeryDenseMergeTool from this answer. Due to the nature of PDF files this only works for PDFs without headers, footers, and similar artifacts.

like image 135
mkl Avatar answered Nov 02 '22 13:11

mkl