Here we will see how can we create a PDF file using the itext library
We have to download itext.jar and keep it in the lib folder. Now the below code will create a pdf file called first.pdf
Java code to generate the PDF file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.io.*; import com.lowagie.text.*; import com.lowagie.text.pdf.PdfWriter; public class FirstPDF { public static void main(String arg[]) throws Exception { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("first.pdf")); document.open(); document.add(new Paragraph("This is my first Pdf file ---")); document.close(); } } |
In the above code you can notice that
1) We are making an object of class Document.This works sa a container. This can be used for describing the document’s properties like page size, margins etc.
2) After creating the document object we are calling the getInstance method of the pdfWriter by passing document object and FileOutputstream object, Which will create PDF file. If the mentioned pdf file doesn’t exist then it will create a pdf file.
3) Open the document by document.open().
4) We can add the content to the document by passing the paragraph object to the add method.
4) Finally close the document by using the document.close(). This method will flush and close the OutputStream instance.
Output of the above code
This code will generate a pfd file called first.pdf with the paragraph content as
This is my first Pdf file —
Leave a Reply