In this tutorial we will see how to write PDF file in Java using iText library.
Review the code listed below. Running this program will generate a PDF file at location c:/itext.pdf. You can change the location in the program to suit your platform:
package com.quicklyjava;
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;
public class JavaWritePDF {
/**
* @param args
*/
public static void main(String[] args) {
try {
File file = new File("c://itext.pdf");
FileOutputStream pdfFileout = new FileOutputStream(file);
Document doc = new Document();
PdfWriter.getInstance(doc, pdfFileout);
doc.addAuthor("QuicklyJava.com");
doc.addTitle("This is title");
doc.open();
Paragraph para1 = new Paragraph();
para1.add("This is paragraph 1");
Paragraph para2 = new Paragraph();
para2.add("This is paragraph 2");
doc.add(para1);
doc.add(para2);
doc.close();
pdfFileout.close();
System.out.println("Success!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Write PDF file in Java using iText code explanation:
1) The line below gets an instance of PDFWriter. The doc object instance can be subsequently used to add content to the PDF
PdfWriter.getInstance(doc, pdfFileout);
2) The lines below adds Author and Title to the PDF file.
doc.addAuthor("QuicklyJava.com");
doc.addTitle("This is title");
3) The line below open the PDF document for writing.
doc.open();
4) The lines below create a Paragraph and add String content to the Paragraph.
Paragraph para1 = new Paragraph();
para1.add("This is paragraph 1");
5) The line below add the Paragraph to the PDF document:
doc.add(para1);
6) Once done with adding content, be sure to close the FileOutputStream and the Document:
doc.close(); pdfFileout.close();
Write PDF file in Java using iText Output:
Tutorials in this series:
You can download the eclipse project of the code explained in this tutorial:




[...] 3. Write PDF file in Java using iText [...]
[...] 3. Write PDF file in Java using iText [...]
Thought it wouldn’t to give it a shot. I was right.