package pdf;

import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.*;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;

/**
 * Update the Existing PDF file.
 * 
 * @author Sandeep
 */

public class ModifyExistingPDF {

	/**
	 * Update the Existing PDF file
	 * 
	 * @param args no arguments needed here
	 */
	public static void main(String[] args) 
	{


		// step 1: creation of a document-object
		Document document = new Document();
		try {
			
            PdfReader reader = new PdfReader("Input.pdf");
            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
			
			// step 2:
			// we create a writer that listens to the document
			// and directs a PDF-stream to a file
			PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Output.pdf"));
			
			// step 3: we open the document
			document.open();

			// step 4: Copy the content of Input PDF to Output PDF
			int i = 0;
			PdfContentByte cb = writer.getDirectContent();
            while (i < n ) 
            {
                document.newPage();
                i++;
                PdfImportedPage page1 = writer.getImportedPage(reader, i);
                cb.addTemplate(page1,0,0);
            }
			
            // step 5 : After copying previous data in file 
            //			add the New content in the File.
            
            // Add the New Page => This is Problem Condition because if we don't 
            // add new page here it ovewrites last page of the Input pdf. 
            document.newPage();
			
            // This is new Content Which needs to be added in pdf file 
            for(int j=0;j<=50;j++)
			{
				document.add(new Paragraph("Hello World " + j));
			}
			
		} 
		catch (DocumentException de) 
		{
			System.err.println(de.getMessage());
		}
		catch (IOException ioe) 
		{
			System.err.println(ioe.getMessage());
		}
		finally
		{
			// step 6: we close the document
			document.close();
		}
	}
}