Modifying PDFs using iText api

Hi there!!!

Using iText, one can create a copy of existing pdf file with desired modification. Also, iText allows us to add acrobat reader javascripts into PDF, which is very useful to add custom command buttons, hiding menubars, toolbars and invoking dialog boxes.

Following java code shows to invoke a print dialog box on opening a pdf file.

import com.lowagie.text.Document; 
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;

import com.lowagie.text.pdf.PdfReader;

Document document = new Document();
PdfReader pdfReader = new PdfReader(fileData); // fileData is a byte[] of existing pdf
PdfCopy writer = new PdfCopy(document, 
new FileOutputStream(writeFile)); // create a pdf copy.;
writer.addJavaScript("this.print();"); //adding javascript //for the print dialog.
int pages = pdfReader.getNumberOfPages();
if(pages > 0) { 
   PdfImportedPage page;
   for(int i=1;i<=pages;i++) { 
      page = writer.getImportedPage(pdfReader, i); //get page       //from the pdf

      writer.addPage(page); // add to the new pdf. 

"writeFile" is a new file which contains a java script to open a print dialog.

Similarly you can import the pdf bookmarks and annotations.

No comments:

Post a Comment