10g. Advanced WebDriver – Saving screenshots to a word document

Hiya Champs! Hope you had a great time taking screenshots and saving them locally. Today, let us see how we can create a word document and insert all images captured as part of a test case into that. Having a separate document for each test case would not only help us keep our workspace organized but also searching for a particular screenshot becomes a piece of cake. And the best part is, we are going to write code so that all this stuff happens automatically without any manual intervention.

Allow me to get straight to the point.

Step 1:

Download a couple JARs to make our jobs easier.

java2word-3.3.jar – Helps us to create a word document and manipulate it the way we want.

xstream-1.3.1.jar – Deals with images

Let us go ahead and download both these JAR files from https://code.google.com/archive/p/java2word/downloads (download location at the time of writing this article). I am placing these JARs in our GitHub repo as well, along with all other code files dealt as part of this post.

Step 2:

Add these JARs to our project build path.

We have seen this procedure numerous times before and hence I am not re-iterating it (Refer to Step 3 of this article for detailed explanation).

Step 3:

Create a class, “SaveDocument.java”.

Add the below code to the class file,

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

import word.api.interfaces.IDocument;
import word.w2004.Document2004;
import word.w2004.Document2004.Encoding;
import word.w2004.elements.BreakLine;
import word.w2004.elements.Heading1;
import word.w2004.elements.Heading3;
import word.w2004.elements.Image;
import word.w2004.elements.Paragraph;
import word.w2004.style.HeadingStyle.Align;

public class SaveDocument {
  public static void createDoc(String testCaseName, String[] imgFileNames) {
    // Create a document object
    IDocument myDoc = new Document2004();
    // Inserts one breakline
    // Add client logo to document header
    // Add Project name to document header
    myDoc.getHeader().addEle(Heading3.with(" ProjectName").withStyle().align(Align.RIGHT).create());
    // Specify Test case name as document heading
        myDoc.addEle(Heading1.with(testCaseName + " Test Case").withStyle().align(Align.CENTER).create());
        // Add a description paragraph
                .with("Following are the related screenshots")
        // Add company name to document footer
        // Loop through all the image files
        for(String file:imgFileNames){
        	// Insert each image file to the document
                                "/Selenium/screenshots/" + file + ".png") 
        	// Insert 2 linebreaks at the end of each inserted image
        // Insert an image from web
        // Create the word document specifying a location
        File fileObj = new File("\\Selenium\\" + testCaseName + ".doc");
        PrintWriter writer = null;
        try {
         writer = new PrintWriter(fileObj);
        } catch (FileNotFoundException e) {
        String myWord = myDoc.getContent();

        // Print a confirmation image to console
        System.out.println("Word document created successfully!");

Comments are provided for each line to make the code self-explanatory.

public static void createDoc(String testCaseName, String[] imgFileNames)  – This method has two arguments. First one is a String which specifies the test case name. This will be the name of the word document that will be created. The second argument is an array of all the screenshot names captured as part of that test case.

And in this method, we are creating a document object and performing operations such as,

  • Adding headings, paragraphs
  • Adding client logo and company name to the header
  • Adding company name to the footer
  • Inserting all the screenshots captured as part of a particular test case
  • Inserting an image from the web (just to prove that this case is also possible)
  • Saving the word document with the name of the test case in a particular location

Step 4:

A few modifications to ‘SaveScreenshot.java’ file.

A couple changes are made to the ‘SaveScreenshot.java’ class we created as part of the previous post.

  1. The function that generates a timestamp is removed and
  2. The file extension is changed from ‘.jpg’ to ‘.png’

The code now looks something like this,

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public class SaveScreenshot {

  public static void capture(String screenshotName, WebDriver driver) {
    // Cast driver object to TakesScreenshot
    TakesScreenshot screenshot = (TakesScreenshot) driver;
    // Get the screenshot as an image File
    File src = screenshot.getScreenshotAs(OutputType.FILE);
    try {
      // Specify the destination where the image will be saved
      File dest = new File("\\Selenium\\screenshots\\" + screenshotName + ".png");
      // Copy the screenshot to destination
      FileUtils.copyFile(src, dest);
    } catch (IOException ex) {

Sample Scenario

  1. Open Firefox browser.
  2. Navigate to google account creation page
  3. Locate first name text box by id
  4. Enter ‘fname01’ as the first name
  5. Take a screenshot and name it as “testCaseName” + “1”
  6. Locate last name text box by name
  7. Enter ‘lname01’ as the last name
  8. Take a screenshot and name it as “testCaseName” + “2”
  9. Create a word document in specified location and insert both these screenshots into it.

JUnit Code:

WordDocWithScreenshotTest.java class

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.blog.utilities.SaveDocument;
import com.blog.utilities.SaveScreenshot;

public class WordDocWithScreenshotTest {
  //Declaring variables
  private WebDriver driver; 
  private String baseUrl;
  private String testCaseName = "WordDocWithScreenshot";

  public void setUp() throws Exception{
    // Selenium version 3 beta releases require system property set up
    System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
        + "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
    // Create a new instance for the class FirefoxDriver
    // that implements WebDriver interface
    driver = new FirefoxDriver();
    // Implicit wait for 5 seconds
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    // Assign the URL to be invoked to a String variable
    baseUrl = "https://accounts.google.com/SignUp";
  public void testPageTitle() throws Exception{
    // Open baseUrl in Firefox browser window
    // Locate First Name text box by id and
    // assign it to a variable of type WebElement
    WebElement firstName = driver.findElement(By.id("firstName"));
    // Clear the default placeholder or any value present
    // Enter/type the value to the text box
    //Take a screenshot
    SaveScreenshot.capture(testCaseName + "1", driver);
    // Locate last name text box by name
    WebElement lastName = driver.findElement(By.name("lastName"));
    // Clear and enter a value
    // Take a screenshot
    SaveScreenshot.capture(testCaseName + "2", driver);
    // Create a word document and include all screenshots
    SaveDocument.createDoc(testCaseName, new String[]{testCaseName + "1",testCaseName + "2"});
    public void tearDown() throws Exception{
    // Close the Firefox browser

The code is self-explanatory if comments are followed. Eclipse output is as below,

Document Eclipse output

In Eclipse IDE, JUnit pane clearly shows that the test case ‘WordDocWithScreenshotTest.java’ has passed and the console has no errors. “Word document create successfully” is printed as expected.

As specified in the code, the screenshots are saved to “E:/Selenium/screenshots” path with the names in the mentioned format.

Saved screenshots

The word document is created and saved in the specified location as well, “E:/Selenium/”. The document looks as follows,

Created Word Document

Created word document, all code files, and JARs are placed in the GitHub repo for easy access. You can star and fork the repository for convenience. Please go through the ‘README.md’ file for clear instructions.

Happy coding! Have a nice day!

Series Navigation<< 10f. Advanced WebDriver – Taking a Screenshot10h. Advanced WebDriver – Sending email with attachments >>

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.