In previous article about Generating PDF files using iText JAR, Kiran Hegde had described a nice and basic way of generating PDF files in Java using iTest JAR. It is a great starter tutorial for those who wants to start working with iText.
In one of the requirement, I had to merge two or more PDF files and generate a single PDF file out of it. I thought of implementing the functionality from scratch in iText, but then thought to google it and see if already someone have written code for what I was looking for.
As expected, I got a nice implementation of java code that merges 2 or more PDF files using iText jar. I thought of dissecting the code in this post and give credit to original author of the post.
Merge PDF files in Java using iText JAR
So here we go. First let us see the code.
If you see what the code does is pretty simple.
- In main() method, we create a List of InputStream objects that points to all the input PDF files we need to merge
- We call MergePDF.concatPDFs() static method passing list of input PDFs, OutputStream object for merged output PDF and a boolean flag that represents whether you need to include page numbers at the end of each page as command line arguments
- In concatPDFs() method, first we convert List of InputStream objects to List of PdfReader objects in first while loop. And also we keep count of the total pages in all the input PDF files.
- Next we create BaseFont object using BaseFont.createFont() method. This will be the font for writing page numbers
- Next we create output objects to write our merged PDF file using Document class object and PdfWriter.getInstance() method
- Finally we write all the input PDFs into merged output PDF iterating each PDF and then writing each page of it in two while loops
- And then, close all the streams and clear all the buffers. Good boys do this
So now we know how to merge PDF files into one, let us see the way to split a PDF file or extract a part of PDF into another PDF.
Split PDF files in Java using iText JAR
Let us see the code.
In above code, we have created a method splitPDF () that can be used to extracts pages out of a PDF and write it into another PDF. The code is pretty much self explanatory and is similar to the one to merge PDF files.
Thus, if you need to split an input.pdf (having 20 pages) into output1.pdf (1-12 pages of input.pdf) and output2.pdf (13-20 of input.pdf), you can call the above method as follow: