In many applications there is a need to generate pdf file dynamically. The iText library can be used to generate PDF documents from Java program.
Add Content of an iText PDF File using java code
In many applications there is a need to generate pdf file dynamically. The iText library can be used to generate PDF documents from Java program. The iText is a open source library that provide facility to create pdf file from java application. iText is a freely available Java library from Lowagie.com, it supports the generation of HTML, RTF, and XML and PDFdocuments. You can use variety of fonts and colors in document. To use iText library you need to import package.....
import com.lowagie.text.*;
In the example given below we will create a pdf file at the specified location. In this example we will first create Document object that has arguments page size, left right top and bottom margins. After that create object of PdfWriter class. Other writers are HtmlWriter, RtfWriter, XmlWriter etc.
CreatePDFiText.java
import com.lowagie.text.Document; import com.lowagie.text.Font; import com.lowagie.text.FontFactory; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Chunk; import com.lowagie.text.pdf.PdfWriter; import com.lowagie.text.pdf.PdfContentByte; public class CreatePDFiText { public static void main(String[] args) { try { Document document = new Document(PageSize. A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance (document, new FileOutputStream("C:\\my.pdf")); document.open(); // create a chunk object using chunk class of itext library. Chunk underlined = new Chunk("This is sample pdf file created by : "); // set the distance between text and line. underlined.setTextRise(8.0f); // set the width of the line, 'y' position, color and design of the line underlined.setUnderline(new Color(0x00, 0x00, 0xFF),0.0f, 0.2f, 3.0f, 0.0f, PdfContentByte.LINE_CAP_PROJECTING_SQUARE); // finally add object to the document. document.add(underlined); document.add(new Paragraph("Mahendra Singh", FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new Color(255, 150, 200))));; document.close(); } catch (Exception e2) { System.out.println(e2.getMessage()); } } } |
Save this java code with .java , before run this code you need to add iText library so first download the .jar file of iText library and add to jdk library. If you are using any IDE, so you can directly add iText library to IDE. After that compile as a java code with javac command and run. This code will create a pdf file on specified location.