iText provides flexible ways for creation and manipulation of PDF files. We will start with steps on how to create simple PDF using itext with some examples.
Setup
Setup can be done by adding Maven dependency.
Add the below dependency into your pom.xml
1 2 3 4 5 |
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.0.6</version> </dependency> |
Or you can directly download the latest itext jar and add it to your class path. Download from maven – iText download
Example on how to create simple PDF using iText
Important classes used are
a) com.itextpdf.text.Document
b) com.itextpdf.text.pdf.PdfWriter
Create a object of the Document class. Create a PdfWriter instance and use the document for writing the pdf to a specified location. For writing into the Pdf, you need to first open the document and then use the add() method. Once writing is done close() the document.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package com.kscodes.examples.itext; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; public class SimplePdf { public static void main(String args[]) { // Create a Document object Document document = new Document(); try { // Create a PdfWriter instance and use the document to write the pdf // to a specified location PdfWriter.getInstance(document, new FileOutputStream("K:\\Kscodes\\pdf\\itext-sample.pdf")); // open the document document.open(); // Add elements to the document document.add(new Paragraph("This is a Simple example of iText")); // close the document document.close(); System.out.println("PDF created at the location !!!"); } catch (Exception e) { System.out.println("Exception occured :: " + e); } } } |
Output
In our next few posts we will see some more examples on iText.