1

I have the following requirement:

First I want to create a PDF dynamically. Then I want the option to upload PDF files. Finally, upon clicking a print button, both the dynamically created and the uploaded files must be merged.

When the print button is clicked, a single method should should create the PDF and combine it with the uploaded PDFs.

This is my code so far.

package com.sumit.program;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfCopy.PageStamp;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSmartCopy;

public class CopyOfMergePdf {

    public static void main(String[] args) {
        try {
            List<InputStream> pdfs = new ArrayList<InputStream>();
            pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\Landscape.pdf"));
            pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\client\\CoverSheet.pdf"));
            pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\client\\ECNPRINTTEST_BP.pdf"));
            pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\Landscape.pdf"));
            pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\Document1.pdf"));
            pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\Landscape.pdf"));
            pdfs.add(new FileInputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\Portrait.pdf"));
            OutputStream output = new FileOutputStream("C:\\Documents and Settings\\Sumit\\Desktop\\NewEcnProject\\merge1.pdf");
            CopyOfMergePdf.concatPDFs(pdfs, output, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void concatPDFs(List<InputStream> streamOfPDFFiles,
            OutputStream outputStream, boolean paginate) {

        Document document = new Document();      
        try {
            List<InputStream> pdfs = streamOfPDFFiles;
            List<PdfReader> readers = new ArrayList<PdfReader>();
            int totalPages = 0;
            Iterator<InputStream> iteratorPDFs = pdfs.iterator(); 
            // Create Readers for the pdfs.
            int i=1;
            while (iteratorPDFs.hasNext()) {
                InputStream pdf = iteratorPDFs.next();
                PdfReader pdfReader = new PdfReader(pdf);
                System.out.println("Page size is "+pdfReader.getPageSize(1));
                readers.add(pdfReader);
                totalPages += pdfReader.getNumberOfPages();
                i++;
            }

            int j=0;
            System.out.println("Total pages are "+totalPages);
            // Create a writer for the outputstream
            PdfCopy copy = new PdfSmartCopy(document, outputStream);
            document.open();    

            PdfImportedPage page;
            PageStamp stamp;
            Chunk chunk;
            BaseFont baseFont = BaseFont.createFont("arial.ttf", BaseFont.CP1252,BaseFont.EMBEDDED);
            Iterator<PdfReader> iteratorPDFReader = readers.iterator();            
            // Loop through the PDF files and add to the output.
           i=0;
           PdfContentByte under;
            while (iteratorPDFReader.hasNext()) {
                PdfReader pdfReader = iteratorPDFReader.next();           
                // loop over the pages in that document                   
                page=copy.getImportedPage(pdfReader,pdfReader.getNumberOfPages());              
                i=i+1;
                stamp = copy.createPageStamp(page);
                chunk = new Chunk(String.format("Page %d",i));               
                chunk.setFont(new Font(baseFont));
                ColumnText.showTextAligned(stamp.getUnderContent(),
                        Element.ALIGN_CENTER, new Phrase(chunk),
                        document.getPageSize().getWidth()/2, 15, 0);

                if(i==2){


                }
                Image watermark_image = Image.getInstance("C:\\Documents and Settings\\Sumit\\Desktop\\ecn_in_pro.png");
                watermark_image.setAbsolutePosition(0,0);           
                under = stamp.getUnderContent();                
                under.addImage(watermark_image);
                stamp.alterContents();
                copy.addPage(page);
                copy.freeReader(pdfReader);
                pdfReader.close();               
            }

            outputStream.flush();
            document.close();
            outputStream.close();
            System.out.println("Merging of Pdfs is done.......");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document.isOpen())
                document.close();
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

It only copies all of the existing PDF files into one new file. How do I add the dynamically created document to the PdfCopy process?

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
Sumit Vaidya
  • 51
  • 1
  • 4
  • How about creating that new content as a separate PDF (which may reside in memory using a `ByteArrayOutputStream`) and including it in the collection of PDFs to merge? – mkl Feb 13 '14 at 15:06
  • I am not creating New Pdf file only document.newPage() and adding some paragraph and Chunk and it will create new page that page i need to show before coping – Sumit Vaidya Feb 13 '14 at 15:13
  • What do you mean by "coping"? Also: I don't understand the question. Do you want to introduce blank pages into `PdfCopy` process? – Bruno Lowagie Feb 13 '14 at 15:35
  • Yeah exactly, but inside that blank page i will add some Paragraph and Chunk text – Sumit Vaidya Feb 13 '14 at 15:37
  • In that case, you need part 2 of my answer, which is exactly what @mkl was trying to explain (but for some reason you failed to understand him). – Bruno Lowagie Feb 13 '14 at 15:43
  • I've edited your question based on the feedback in your comments. – Bruno Lowagie Feb 13 '14 at 15:54
  • @SumitVaidya It's custom to accept/upvote answers if they were helpful. – Bruno Lowagie Feb 13 '14 at 17:47

1 Answers1

2

If you want to insert an empty page in the PdfCopy process, you should use the addPage() method that takes a Rectangle and a rotation (int) as parameter.

If you want to insert an "on-the-fly" page that has content in the PdfCopy process, you need to create a document in memory, add content to that page and treat that page the same way as you treat the documents you read from disk.

Something like this:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter.getInstance(document, baos);
document.open();
document.add(new Paragraph("This page is empty on purpose"));
document.close();
PdfReader reader = new PdfReader(boas.toByteArray());

If, for instance, you want to add a cover page, you'd also create a document in memory first, for instance listing all the documents that are being merged.

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165