6.8.  PDF Documents on Web Sites

Initial Situation

You are providing generated PDF documents on your web pages.

Problem

The PDF can only be tested in the context of the web pages. So, the input data for a test has to be entered to the browser frontend and the generated PDF has to be selected also through the web page.

Solution Approach

Selenium provides a good way to select a PDF document from a web page. This document will be opened by PDFUnit as a Stream.

Solution

The following lines represent the main part of the test:

/**
 * When the URL of the pdf document inside an HTML page is generated dynamically,
 * you have to find the link (href) first.
 * Input data for the web page can also be typed with Selenium (not shown here).
 */
@Test
public void verifyPDF_LoadedBySeleniumWebdriver() throws Exception {
  // arrange, navigate to web site:
  String startURL = "http://www.unicode.org/charts/";
  driver.get(startURL);
  WebElement element = driver.findElement(By.linkText("Basic Latin (ASCII)"));
  String hrefValue = element.getAttribute("href");
  
  // act, load PDF web site:
  URL url = new URL(hrefValue);
  
  // assert, validate PDF:
  String expectedTitle  = "The Unicode Standard, Version 6.3";

  AssertThat.document(url)
            .hasTitle().equalsTo(expectedTitle)
  ;
  AssertThat.document(url)
            .restrictedTo(FIRST_PAGE)
            .hasText()
            .containing("0000", "007F")
  ;
}

The remaining lines are:

/**
 * This sample shows how to test a PDF document with Selenium and PDFUnit.
 * See the previous code listing for the '@Test' method. 
 *
 * @author Carsten Siedentop, March 2012
 */
public class PDFFromWebsiteTest {

  private WebDriver driver;

  @Before
  public void createDriver() throws Exception {
    driver = new HtmlUnitDriver();
    Logger htmlunitLogger = Logger.getLogger("com.gargoylesoftware.htmlunit");
    htmlunitLogger.setLevel(java.util.logging.Level.SEVERE); 
  }
  
  @After
  public void closeAll() throws Exception {
    driver.close();
  }
  
  // @Test
  // public void verifyPDF_LoadedBySeleniumWebdriver()...

}

For more information about Selenium contact the project site http://seleniumhq.org/.