How to generate PDF report in Selenium with TestNG & iTextPDF?

We know that presentation matters for testing, so, it is always good to present a well-elaborated test report before the test manager. We have discussed a lot about different techniques of test report generation in Selenium, and logging with Log4j, ITestListener, and WebDriverListener. All these are the way to represent test execution in an elaborated manner. Today we are going to add another milestone in test reporting and it is about creating a PDF report of the entire test execution.

We will use the iText JAR file for pdf report generation and further we will integrate it with TestNG reporting. Hence, basically, we will use iText PDF with TestNG’s IReporter listener.

Before we go the implementation of PDF report generation functionality in our Selenium project, let’s have a look over some of the test report and log generation techniques in Selenium:

These are some of the awesome articles which will definitely help you in building your knowledge base.

Pre-Requisites for PDF report generation in Selenium

There are some pre-requisites for PDF report generation in Selenium. Those pre-requisites are listed as below:

  • Your project should be configured with iText Java API. Click here to download iText API. Once you have downloaded the JAR file, then add it to your project. I believe you know the steps to add external JAR files.
  • If you are using Maven, then you can create dependencies for the iText JAR file. Click here to get the maven dependencies.

Java definition of iText declaration to write to the PDF file

Following code is the Java definition to create a PDF file and addition of some para to the newly created file.

String fileName = "filename.pdf";
FileOutputStream fos = new FileOutputStream(fileName);
Document doc = new Document();
PdfWriter.getInstance(doc, fos);
doc.open();
doc.addAuthor("authorName");
doc.addTitle("title");
doc.addSubject("description");
doc.add(new Paragraph("This is paragraph"));
doc.close();

Explanation of the code

Here firstly we are creating the String definition of the path of the PDF file. Then, the instance of Document class creates a new PDF file. Further, PdfWriter.getInstance method is used give the path of the file. Further open() and close() method is used to open and close the file respectively. Meanwhile, open and close, we declared Author name, Title, Subject and Paragraph of the PDF report with addAuthor, addTitile, addSubject and add(new Paragraph()) methods respectively.

Steps to generate PDF report in Selenium

We will carefully implement above logic to generate PDF report with our test execution data. Let’s begin.

Step# 1: Create a separate class to define PDF actions

Here we create a separate class in which we have created a separate method for each action. Following code elaborate this step.

CreatePDFReport.java

package Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;




public class CreatePDFReport {
	
	Document doc;
	
	public void openPdfPath() throws FileNotFoundException, DocumentException{
		
		String fileName = new File("").getAbsoluteFile().toString()+"/TestReport/pdf-"+System.currentTimeMillis()+".pdf";
		
		FileOutputStream fos = new FileOutputStream(fileName);
		
		doc = new Document();
		
		PdfWriter.getInstance(doc, fos);
		
		doc.open();
	}
	
	public void addMetaData(String authorName, String title, String description){
		doc.addAuthor(authorName);
		doc.addTitle(title);
		doc.addSubject(description);
	}
	
	public void addParagraph(String text) throws DocumentException{
		doc.add(new Paragraph(text));
	
	}

	public void closePdf(){
		doc.close();
	}
	

}

Step# 2: Implement IReporter and Merge with methods of CreatePDFReport.java

Now implement IReporter for test reporting and add the data to the PDF file by extending CreatePDFReport.java. Following code explains this step.

SeleniumPDFReportWithIReporter.java

package Test;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.testng.IReporter;
import org.testng.IResultMap;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.xml.XmlSuite;

public class SeleniumPDFReportWithIReporter extends CreatePDFReport implements IReporter{

	@Override
	public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
		
for(ISuite ist : suites){
	try{
		//Calling open pdf method
				openPdfPath();
				//*************//
				
		Map<String, ISuiteResult> resultSuiteMap = ist.getResults();
		
		Set<String> key = resultSuiteMap.keySet();
		
		for(String k : key){
			
			ITestContext cntx = resultSuiteMap.get(k).getTestContext();
			
			System.out.println("Suite Name- "+cntx.getName()
								+"\n Report Directory- "+cntx.getOutputDirectory()
								+"\n Test Suite Name- "+cntx.getSuite().getName()
								+ "\n Start Date and Time of Execution- "+cntx.getStartDate()
								+ "\n End Date and Time of Execution- "+cntx.getEndDate());
			
			//*********Printing above details in pdf file*******//
			addParagraph("Suite Name- "+cntx.getName()
								+"\n Report Directory- "+cntx.getOutputDirectory()
								+"\n Test Suite Name- "+cntx.getSuite().getName()
								+ "\n Start Date and Time of Execution- "+cntx.getStartDate()
								+ "\n End Date and Time of Execution- "+cntx.getEndDate());
			
			//************************************************************//
			
			IResultMap failedTest = cntx.getFailedTests();
			
			
			Collection<ITestNGMethod> failedMethods = failedTest.getAllMethods();
			
			System.out.println("------Failed Test Case-----");
			
			for(ITestNGMethod imd : failedMethods){
				
				System.out.println("Test Case Name- "+imd.getMethodName()
				+"\n Description- "+imd.getDescription()
				+"\n Priority- "+imd.getPriority()
				+ "\n Date- "+new Date(imd.getDate()));
				
				
				//*********Printing failed details in pdf file*******//
				addParagraph("Test Case Name- "+imd.getMethodName()
				+"\n Description- "+imd.getDescription()
				+"\n Priority- "+imd.getPriority()
				+ "\n Date- "+new Date(imd.getDate()));
				
				//************************************************************//
				
				
			}
			
			
			
			IResultMap passedTest = cntx.getPassedTests();
			
			
			Collection<ITestNGMethod> passedMethods = passedTest.getAllMethods();
			
			System.out.println("------Passed Test Case-----");
			
			for(ITestNGMethod imd1 : passedMethods){
				
				System.out.println("Test Case Name- "+imd1.getMethodName()
				+"\n Description- "+imd1.getDescription()
				+"\n Priority- "+imd1.getPriority()
				+ "\n Date- "+new Date(imd1.getDate()));
				
				//*********Printing passed details in pdf file*******//
				addParagraph("Test Case Name- "+imd1.getMethodName()
				+"\n Description- "+imd1.getDescription()
				+"\n Priority- "+imd1.getPriority()
				+ "\n Date- "+new Date(imd1.getDate()));
				
				//************************************************************//
				
			}
		}
	
	//Closing PDF file
		closePdf();
		
		
	}catch (Exception e){
		e.printStackTrace();
	}
}

	}
	
		
	

}

Step# 3: Create any TestNG tests to validate the PDF report generation

Following test program contains two scenarios, in which, the first scenario fails the test and second scenario will pass the test. Further, reporting will be printed in PDF, Custom TestNG report and console as well.

MySampleTestPDFFile.java

package Test;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class MySampleTestPDFFile {
	WebDriver driver;
	

	@BeforeClass
	public void setUp(){
		System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe");
	  	 
	  	  driver  = new ChromeDriver();
	  	  
	  	  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		  
	  	  driver.get("https://www.inviul.com/");
		  
	  	  driver.manage().window().maximize();
	}
	
	@AfterClass
	public void tearDown(){
		
		driver.close();
		  
		driver.quit();
		
	}
	
	
  @Test(priority=1, description="My Sample Test Fail Reported in PDF")
  public void testMethod1() {
	 
  	  String expectedTitle = "TestingFailed";
  	  
  	  Assert.assertEquals(driver.getTitle(), expectedTitle, "Title not matched"); 
	  
  }
  
  @Test(priority=0, description="My Sample Test Pass Reported in PDF")
  public void testMethod2() {
  	  
  	  boolean matchCondition = driver.getTitle().contains("Selenium");
  	  
  	  Assert.assertTrue(matchCondition, "Title matched");
	  
  }
}

Step# 4: testng.xml

Now run the sample program from the testng.xml file. Here do not forget to add the listeners.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Inviul Sample Test Suite">
<listeners>
 <listener class-name="Test.SeleniumPDFReportWithIReporter"/>
 <listener class-name="Test.ListenersDefinitionClass"/>
</listeners>
<!-- Test -->
  <test name="Inviul Test" >
    <classes>
      <class name="Test.MySampleTestPDFFile"/>
    </classes>
  </test> 
  <!-- End Test -->
  
</suite> <!-- Suite -->

PDF Report Generated

PDF Report in project

Console Output

Console output of PDF Report

PDF File

PDF Report Test execution

This was all about PDF report generation in the Selenium project. You can post your queries below and don’t forget to join our Facebook group for quick support.

Join Inviul fb group

16 Comments

Leave a Reply