Friday 16 September 2016

itext: Hello World Application

In this post, I am going to explain how to create a pdf document. Following step-by-step procedure explains, how to create and write the message “Hello World” to the pdf document.

Step 1: Create Document instance.
Document document = new Document();

Step 2: Get the instance of PdfWriter, by passing the Document instance and pdf file name as arguments.

PdfWriter.getInstance(document, new FileOutputStream("empty.pdf"));

Step 3: Open pdf document, write some data and close the document.

document.open();
document.add(new Paragraph("Hello World!"));
document.close();

Following is the complete working application.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

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

public class HelloWorld {
 public static void main(String args[]) throws FileNotFoundException, DocumentException {
  Document document = new Document();
  PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
  document.open();
  document.add(new Paragraph("Hello World!"));
  document.close();
 }
}


Run above application, you can able to see ‘hello.pdf’ file with message ‘Hello World!’ in it.

Previous                                                 Next                                                 Home

No comments:

Post a Comment