Tuesday, July 8, 2008

Dynamically Generate PDF

We can generate the PDF dynamically.Here i will explain about the PDF geneartion with the iText Library.

History Of iText:

iText is a library that allows you to generate PDF files on the fly.

iText is an ideal library for developers looking to enhance web- and other applications with dynamic PDF document generation and/or manipulation. iText is not an end-user tool. Typically you won't use it on your Desktop as you would use Acrobat or any other PDF application. Rather, you'll build iText into your own applications so that you can automate the PDF creation and manipulation process.

For instance in one or more of the following situations:
Due to time or size, the PDF documents can't be produced manually.
The content of the document must be calculated or based on user input.
The content needs to be customized or personalized.
The PDF content needs to be served in a web environment.
Documents are to be created in "batch process" mode.
You can use iText to:
Serve PDF to a browser
Generate dynamic documents from XML files or databases
Use PDF's many interactive features
Add bookmarks, page numbers, watermarks, etc.
Split, concatenate, and manipulate PDF pages
Automate filling out of PDF forms
Add digital signatures to a PDF file

Process :

1. Decide where store the PDF.In web Apllication it should be stored in server.

String obsPath = this.getRequest().getContextPath();
String RealPath = this.getRequest().getRealPath(obsPath);
File ptfFile=null;
String path = RealPath.substring(0,RealPath.lastIndexOf(File.separator));
ptfFile = new File(path + File.separator + "Generated PDF");
if(!ptfFile.exists()){
ptfFile.mkdir();
}
ptfFile = new File(path + File.separator +"Generated PDF"+
File.separator+"test"+".pdf");


The above code check once before create the pdf if already exists or not.If exists it will updat the existing PDF file.

2. Create the Document and PDFWriter Object.

Document document = null;
PdfWriter writer=null;
document = new Document(PageSize.A4);
writer=PdfWriter.getInstance(document, new FileOutputStream(ptfFile));

3. Open the Document to write the content of the PDF.

document.open();
document.setMargins(document.leftMargin()-40, document.rightMargin()-40,
document.topMargin()+30, document.bottomMargin() -
18);
document.newPage();
form.setFilePath("Generated PDF"+ File.separator+"test"+".pdf");
Phrase phrase = new Phrase(new Chunk(form.getFilePath(),font8));
document.add(phrase);
document.close();


You can set the margine of the PDF using setMargine() function of the document object.

Now the PDF has been generated and stotred in the Specified path.you can open the PDF when the user needs.

No comments: