File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes Merging two pdfs Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Merging two pdfs" Watch "Merging two pdfs" New topic

Merging two pdfs

Palak Agarwal

Joined: Nov 02, 2011
Posts: 21
hi all,

I am trying to merge two pdfs using java code. the following code merges the required pdf but the second pdf gets zoomed.I am using iText java library for this code.
Does anybody have idea, for this behaviour of code.
Kindly help me with this issue.

public static void concatPDFs(List<InputStream> streamOfPDFFiles,

OutputStream outputStream, boolean paginate) {

Document document = new Document(PageSize.A2);

try {
List<InputStream> pdfs = streamOfPDFFiles;
List<PdfReader> readers = new ArrayList<PdfReader>();
int totalPages = 0;
Iterator<InputStream> iteratorPDFs = pdfs.iterator();

// Create Readers for the pdfs.
while (iteratorPDFs.hasNext()) {
InputStream pdf =;
PdfReader pdfReader = new PdfReader(pdf);
totalPages += pdfReader.getNumberOfPages();
// Create a writer for the outputstream
PdfWriter writer = PdfWriter.getInstance(document, outputStream);;
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
// data

PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();

// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader =;

// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
page = writer.getImportedPage(pdfReader,

cb.addTemplate(page, 0, 0);

// Code for pagination.
if (paginate) {
//cb.rectangle (document.left (), document.bottom (), document.right ()-document.left (),
// ()-document.bottom ());
cb.setFontAndSize(bf, 10);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
+ currentPageNumber + " of " + totalPages, 520,
5, 0);
pageOfCurrentReaderPDF = 0;
} catch (Exception e) {
} finally {
if (document.isOpen())
try {
if (outputStream != null)
} catch (IOException ioe) {

with regards
I agree. Here's the link:
subject: Merging two pdfs
Similar Threads
How to convert simple Java Code into amazon's AMI
Writing large files to the servletoutputstream in chunks
Disable PDF access permissions like Save/Save As/Print
Covert a PDF to PDF/A format using iText
Save edited pdf Page in A4 size using itext