Thursday, August 12, 2010

Create PDF File using Java

iText is basically PDF library using which one can
  • Generate documents and reports based xml or database
  • One can add bookmarks, page numbers, watermarks, and other features in existing pdf documents
  • Create PDF document with pages
  • Split or merge pages
  • Serve PDF to browsers
There are other features provided by iText. Please refer to  iText Site for more details.

Please note that example mentioned here is only for learning purpose and You should refer to iText licensing before using.

Java program to create PDF using Java and iText follows as :


 /** To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anuj.thirdparties;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

/**
 *
 * @author Anuj Patel
 */
public class PDFOperations {

    protected void createPDF(){
        try {
            OutputStream file = new FileOutputStream(new File("C:\\Anuj.pdf"));
            Document document = new Document();
            PdfWriter.getInstance(document, file);

            document.open();
            document.addAuthor("Anuj j patel");
            document.addCreationDate();
            document.addCreator("Anuj Patel");
            document.addTitle("Sample PDF using Java");
            document.add(new Paragraph("Hello Anuj"));
            document.add(new Paragraph(new Date().toString()));
            document.close();
            file.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        PDFOperations pDFOperations = new PDFOperations();
        
        //create PDF
        pDFOperations.createPDF();        
    }
}


You may want to refer To :

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

3 comments:

  1. Good blog. I found this code extremely useful in my application to create PDF files from various input files by just adding a minor functionality in the above code. Thanks for sharing the information.
    PDF signature

    ReplyDelete
  2. Thanks for sharing this code i mostly use Aspose.PDF for java for creating my pdf files online because i dnt install adobe on my pc for the obvious reasons and its a good API and very secure.

    ReplyDelete