Convert jpg to pdf using iText Library

Ruchi Sharma
2 min readApr 6, 2022

During automation, I came across a scenario where I have to share the screenshots of all the failed test cases along with the Test Report.

Isn’t it a feasible way to send a pdf file containing screenshots of failed test cases instead of sending each screenshot separately over an email?

HOW TO CREATE A PDF FILE?

We can achieve this task by using the iTextPdf Library. You can get the dependency from here.

Add the following dependency in your pom.xml file.

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

Here are the lines of code:

/**
* Method to create a PDF containing all the screenshots of failed test cases.
*/
public void createPDF()
{
try
{
//Setting up the font
Font f=new Font(Font.FontFamily.TIMES_ROMAN,50.0f,Font.BOLD, BaseColor.BLUE);
//Get all the screenshots
List<File> imagesList = getFiles(USER_DIRECTORY + "/screenshots");
Image im = Image.getInstance(imagesList.get(0).getAbsolutePath());
im.setAbsolutePosition(0,0);

Document doc = new Document(im);
//Check for the reports folder
File folder = new File(USER_DIRECTORY + "/reports");
if(!folder.exists())
folder.mkdir();

//Write content in the PDF
PdfWriter.getInstance(doc, new FileOutputStream(USER_DIRECTORY + "/reports/results.pdf"));
doc.open();
doc.addTitle("Failed Cases Screenshots");
doc.addAuthor("Ruchi");
for (File file : imagesList)
{
Paragraph para = new Paragraph(file.getName(), f);
para.setAlignment(Element.ALIGN_RIGHT);
im = Image.getInstance(file.getAbsolutePath());
doc.newPage();
im.setAbsolutePosition(0,0);
doc.add(para);
doc.add(im);
}
doc.close();
}
catch (Exception exception)
{
exception.printStackTrace();
}
}

That’s it! Your pdf is ready.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response