Java code to generate a PDF

Steps
  1. From category directory, select  Java and from project directory, select Java Application, click Next.
  2. Set the project name as PDFWriter and deselect the Create Main Class option, so to name the class and package by your own choice, click Finish.
  3. Now you can see two files,Source Package and Libraries under the project name  PDFWriter.
  4. For this you need to have one Java Main Class and one jar file,itextpdf-5.2.0.jar(Download it).
  5. Right click the  Source Package, select New->Other->Java->Java Main Class.
  6. Set the name of the Java Main Class File as FirstPDF and set the package name as pdfJava, click Finish.
  7. Right click the Libraries,select Add Jar/Folder and then  add itextpdf-5.2.0.jar  the downloaded location.
  8. Now double click the  FirstPDF.java, remove the existing code and  paste the following code.
--------------------------------------------- FirstPDF.java--------------------------------------------------------

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

package pdfJava;

/**
 *
 * @author ZISSAN
 */
import java.io.FileOutputStream;
import java.io.IOException;

//import com.lowagie.text.Document;
//import com.lowagie.text.DocumentException;
//import com.lowagie.text.Paragraph;
//import com.lowagie.text.pdf.PdfWriter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class   FirstPDF{
 /**
* Generates a PDF file with the text 'Hello World'
*/
public static void main(String[] args) {

System.out.println("Hello World");

// Step1:  A document-object is created
Document document = new Document();
try {
// Step2:A writer is created that listens to the document and directs a  PDF-stream to a file.
PdfWriter.getInstance(document, new FileOutputStream("C:/PDF/FirstPdf.pdf"));
//"C:/PDF/FirstPdf.pdf" is the location at which pdf by name FirstPdf.pdf will be created,PDF is the folder //name in "C" drive.
// Step3: Open the document
document.open();
// Step4: Add a paragraph to the document
document.add(new Paragraph("Hello world"));
} catch (DocumentException dex) {
System.err.println(dex.getMessage());
} catch (IOException ioex) {
System.err.println(ioex.getMessage());
}

// Step 5: Close the document
document.close();
System.out.println("PDF is created sussecefully ");
}   
}
---------------------------------------------- FirstPDF.java----------------------------------------------------------------
For using this code in jsp,you can contact me through mail.

No comments:

Post a Comment