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

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts