Searching...
Friday, 22 November 2013

How to create pdf document in java?

20:18

Itext PDF is an open source API that allows to create and modify pdf documents in java. In this example we will see how to create a simple pdf document using Itext.

1. Create a Maven project and add below dependency.

                 <dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.0.6</version>
		</dependency>

2. Create a Main program to create pdf

package com.pretech;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class JavaPDFExample {
	public static void main(String[] args) {
		Document document = new Document(PageSize.A4);
		try {
			PdfWriter.getInstance(document, new FileOutputStream(
					"myfirstpage.pdf"));
			document.open();
			Paragraph paragraph = new Paragraph("Hello world..");
			document.add(paragraph);
			document.close();
			System.out.println("PDF file created");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}

3. Output



image


0 comments: