Tuesday, September 10, 2024

Create Pdf with ITEXT

 ITEXT is one of the most common libraries used to create pdf files. you can get the library from the maven repository. below is the latest version as of now.

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.4</version>
</dependency>

If you have fair knowledge in java, it is more than enough to create a use Itext and generate a PDF file.

you can create a java project, mostly a springboot project via https://start.spring.io/

Then you can add the maven dependency. Here i use maven, but you can use anything eg:gradle

In this example i have added

1. plain text

2. some Alignment with text

3. insert an image ( keep image in classpath)

package com.example.poc.pdf.itext.sample;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

public class ExperienceLetter {

private static String FILE = "C:\\Project\\PoC\\docs\\Experience.pdf";

private static Font TO = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
private static Font TO_DATA = new Font(Font.FontFamily.TIMES_ROMAN, 12);
private static Font TITLE = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD | Font.UNDERLINE);

private static Font BODY = new Font(Font.FontFamily.TIMES_ROMAN, 11);

public static void main(String[] args) {
try {
//create Doc
Document document = new Document();
// pdf file
PdfWriter.getInstance(document, new FileOutputStream(FILE));
//open doc
document.open();
// add each section
// add metadata
addMetaData(document);
//
addParaTo(document);
addTitle(document);

addBody(document, "EMPLYEE NAME", "DESIGNATION", "2022-01-01", "2024-02-01", 2);

addSignature(document);
// close doc
document.close();
} catch (DocumentException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

public static void addMetaData(Document document) {
document.addTitle("Sample Pdf");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Amal Prasad");
document.addCreator("Amal Prasad");
}

public static void addParaTo(Document document)
throws DocumentException {
Paragraph toPara = new Paragraph();
addEmptyLine(toPara, 1);
// Lets write a big header
toPara.add(new Paragraph("TO:", TO));

addEmptyLine(toPara, 1);
toPara.add(new Paragraph("Employee Name", TO_DATA));
toPara.add(new Paragraph("Employee ID:", TO_DATA));
toPara.add(new Paragraph("Address Line 1", TO_DATA));
toPara.add(new Paragraph("Address Line 2", TO_DATA));
toPara.add(new Paragraph("City", TO_DATA));
toPara.add(new Paragraph("Country", TO_DATA));

document.add(toPara);
}

public static void addTitle(Document document)
throws DocumentException {
// create Para
Paragraph title = new Paragraph();
title.setAlignment(Element.ALIGN_CENTER);
addEmptyLine(title, 2);
title.add(new Paragraph("TO WHOM IT MAY CONCERN", TITLE));
title.setAlignment(Element.ALIGN_CENTER);

//add para to doc
document.add(title);
}

public static void addBody(Document document, String employeeName, String designation, String workStartDate, String workEndDate, int yearsOfExperience)
throws DocumentException {
StringBuilder experience = new StringBuilder("This letter is to certify that ");
experience.append(employeeName);
experience.append(" has worked in our organisation as ");
experience.append(designation);
experience.append(".");

experience.append("He had started working here on dated ");
experience.append(workStartDate);
experience.append(" and worked till dated ");
experience.append(workEndDate);
experience.append(".");


experience.append("He had served the company for about ");
experience.append(yearsOfExperience);
experience.append(" years.");
// create Para
Paragraph body = new Paragraph();

addEmptyLine(body, 2);
body.add(new Paragraph(experience.toString(), BODY));

//add para to doc
document.add(body);

// create Para
Paragraph bodyPart2 = new Paragraph();
addEmptyLine(bodyPart2, 1);
StringBuilder expereincePart2 = new StringBuilder("Until the day he joined, he had been quite responsible.");
expereincePart2.append("To date, he has accumulated a diverse set of talents and job experiences");
expereincePart2.append("His mind blowing abilities include: Team work,Management skills and Analytical skills");
expereincePart2.append("");

bodyPart2.add(new Paragraph(expereincePart2.toString(), BODY));
document.add(bodyPart2);

Paragraph bodyPart3 = new Paragraph();
addEmptyLine(bodyPart3, 1);

StringBuilder expereincePart3 = new StringBuilder("We wish him all the best for his future endeavours.");

bodyPart3.add(new Paragraph(expereincePart3.toString(), BODY));

addEmptyLine(bodyPart3, 1);
document.add(bodyPart3);
}

public static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}

public static void addSignature(Document document) throws URISyntaxException, DocumentException, IOException {
String imagePath = "signature.jpg";
Path path = Paths.get(ClassLoader.getSystemResource(imagePath).toURI());
// System.out.println(path.toAbsolutePath());
// String classpath = System.getProperty("java.class.path");
// String[] classpathEntries = classpath.split(File.pathSeparator);
// System.out.println(Arrays.toString(classpathEntries));
Image signImage = Image.getInstance(path.toAbsolutePath().toString());
// signImage.setAlignment(Image.LEFT | Image.TEXTWRAP);
signImage.setAlignment(Image.ALIGN_CENTER);
// signImage.setBorder(Image.BOX);
// signImage.setBorderWidth(15);
signImage.scaleToFit(100, 100);

document.add(signImage);

//////
// create Para
Paragraph afterSignature = new Paragraph();
// addEmptyLine(afterSignature, 3);
afterSignature.add(new Paragraph("Authorized Signatory", BODY));
document.add(afterSignature);
}


}


Explaining the main functionalities

1. Create a Document

//create Doc
Document document = new Document();

2. Create PDF writer instance to write input to generating pdf.

// pdf file
PdfWriter.getInstance(document, new FileOutputStream(FILE));

3. As we have added writer, Now let's open doc.

//open doc
document.open();

4. Do the functionalities/ or operations you need.

eg: add Meta data for the pdf. This also not need. BUt you can add , if you need.

public static void addMetaData(Document document) {
document.addTitle("Sample Pdf");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Alex Crow");
document.addCreator("Alex Crow");
}

you can add Text as Paragraph. Below example will help. Here we create a Paragraph. add content as Paragraphs.  After that add the Paragraph to the document, you already opened.

public static void addParaTo(Document document)
throws DocumentException {
Paragraph toPara = new Paragraph();
addEmptyLine(toPara, 1);
// Lets write a big header
toPara.add(new Paragraph("TO:", TO));

addEmptyLine(toPara, 1);
toPara.add(new Paragraph("Employee Name", TO_DATA));
toPara.add(new Paragraph("Employee ID:", TO_DATA));
toPara.add(new Paragraph("Address Line 1", TO_DATA));
toPara.add(new Paragraph("Address Line 2", TO_DATA));
toPara.add(new Paragraph("City", TO_DATA));
toPara.add(new Paragraph("Country", TO_DATA));

document.add(toPara);
}

you can use below functionality to add some empty lines

public static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}

Add Image

    public static void addSignature(Document document) throws URISyntaxException, DocumentException, IOException {
String imagePath = "signature.jpg";
Path path = Paths.get(ClassLoader.getSystemResource(imagePath).toURI());
Image signImage = Image.getInstance(path.toAbsolutePath().toString());
signImage.setAlignment(Image.ALIGN_CENTER);
signImage.scaleToFit(100, 100);

document.add(signImage);
}

Here we have added an image of an signature.

5. Finally Close the doc.

// close doc
document.close();