How to create pdf document in java?

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


No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts