Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4537

Guide to PDFUnit

$
0
0

1. Introduction

In this article, we’re going to explore the PDFUnit library for testing PDFs.

Using the powerful APIs provided by PDFUnit, we can work with PDFs and verify text, images, bookmarks and a number of other things.

We can eventually write quite complex test-cases using PDFUnit, but let’s start with the most common use cases that will apply to most of your production PDFs and provide an excellent base for further development.

Important note: PDFUnit is available for free for evaluation purposes but not for commercial use.

2. Installation and Setup

The current version of PDFUnit (2016.05) is not available in the Maven Central repository. Hence, we need to download and install jars manually. Please follow the instructions on the official site for manual installation.

3. Number of Pages

Let’s start with a simple example that simply validates the number of pages in a given PDF file:

@Test
public void givenSinglePage_whenCheckForOnePage_thenSuccess() {
 
    String filename = getFilePath("sample.pdf");
    AssertThat.document(filename)
      .hasNumberOfPages(1);
}

The getFilePath() is a simple method, not related to PDFUnit, which simply returns the path of the PDF file as a String.

All the PDFUnit tests start with a call to AssertThat.document() which prepares the document for testing. The hasNumberOfPages() takes an int as the argument which specifies the number of pages the PDF must contain. In our case, the file sample.pdf contains only one page, so the test succeeds.

If the actual number of pages does not match with the argument, an exception is thrown.

Let’s see an example on how to test a scenario when an exception is thrown:

@Test(expected = PDFUnitValidationException.class)
public void givenMultiplePages_whenCheckForOnePage_thenException() {
    String filename = getFilePath("multiple_pages.pdf");
    AssertThat.document(filename)
      .hasNumberOfPages(1);
}

In this case, the file multiple_pages.pdf contains multiple pages. Hence a PDFUnitValidationException exception is thrown.

4. Password Protected Files

Handling password protected files is again really simple. The only difference is in the call to AssertThat.document() where we need to pass a second argument which is the password of the file:

@Test
public void givenPwdProtected_whenOpenWithPwd_thenSuccess() {
    String filename = getFilePath("password_protected.pdf");
    String userPassword = "pass1";

    AssertThat.document(filename, userPassword)
      .hasNumberOfPages(1);
}

5. Text Comparison

Let’s now compare a test PDF (sample.pdf) against a reference PDF (sample_reference.pdf). If the text of the file under test is same as the reference file, then the test succeeds:

@Test
public void whenMatchWithReferenceFile_thenSuccess() {
    String testFileName = getFilePath("sample.pdf");
    String referenceFileName = getFilePath("sample_reference.pdf");

    AssertThat.document(testFileName)
      .and(referenceFileName)
      .haveSameText();
}

The haveSameText() is the method that does all the work of comparing the text between the two files.

If we don’t want to compare the complete text between two files and instead, want to validate the existence of a particular text on a certain page, the containing() method comes handy:

@Test
public void whenPage2HasExpectedText_thenSuccess() {
 
    String filename = getFilePath("multiple_pages.pdf");
    String expectedText = "Chapter 1, content";
 
    AssertThat.document(filename)
      .restrictedTo(PagesToUse.getPage(2))
      .hasText()
      .containing(expectedText);
}

The above test succeeds if the Page #2 of the multiple_pages.pdf file contains the expectedText anywhere on the page. The absence or presence of any other text apart from the expectedText does not affect the results.

Let’s now make the test more restrictive by validating if a particular text is present in a certain region of a page instead of the whole page. For this, we need to understand the concept of PageRegion.

PageRegion is a rectangular sub-section within the actual page under test. The PageRegion must completely fall under the actual page. If any portion of PageRegion falls outside the actual page, it will result in an error.

PageRegion is defined by four elements:

  1. leftX – the number of millimeters a verticle line is away from the leftmost vertical edge of the page
  2. upperY – the number of millimeters a horizontal line is away from the topmost horizontal edge of the page
  3. width – the width of the region in millimeters
  4. height – the height of the region millimeters

To understand this concept better, let us create a PageRegion using the following attributes:

  1. leftX = 20
  2. upperY = 10
  3. width = 150
  4. height = 50

Here is an approximate image representation of the above PageRegion:

Once the concept is clear, the corresponding test case is relatively simpler:

@Test
public void whenPageRegionHasExpectedtext_thenSuccess() {
    String filename = getFilePath("sample.pdf");
    int leftX = 20;
    int upperY = 10;
    int width = 150;
    int height = 50;
    PageRegion regionTitle = new PageRegion(leftX, upperY, width, height);

    AssertThat.document(filename)
      .restrictedTo(PagesToUse.getPage(1))
      .restrictedTo(regionTitle)
      .hasText()
      .containing("Adobe Acrobat PDF Files");
}

Here, we have created a PageRegion within page #1 of the PDF file and verified the text in this region.

6. Bookmarks

Let’s see a couple of bookmark related test cases:

@Test
public void whenHasBookmarks_thenSuccess() {
    String filename = getFilePath("with_bookmarks.pdf");

    AssertThat.document(filename)
      .hasNumberOfBookmarks(5);
}

This test will succeed if the PDF file has exactly five bookmarks.

The label of bookmarks can be verified as well:

@Test
public void whenHasBookmarksWithLabel_thenSuccess() {
    String filename = getFilePath("with_bookmarks.pdf");

    AssertThat.document(filename)
      .hasBookmark()
      .withLabel("Chapter 2")
      .hasBookmark()
      .withLinkToPage(3);
}

Here we are checking that the given PDF has a bookmark with the text “Chapter 2”. It also verifies if there is a bookmark that links to Page #3.

7. Images

Images are another important aspect of PDF documents. Unit testing the images inside the PDF again very easy:

@Test
public void whenHas2DifferentImages_thenSuccess() {
    String filename = getFilePath("with_images.pdf");

    AssertThat.document(filename)
      .hasNumberOfDifferentImages(2);
}

This test verifies that there are exactly two different images utilized inside the PDF. The number of different images refers to an actual number of images stored inside a PDF document.

However, it could be possible that there is a single logo image stored inside the document but is displayed on every page of the document. This refers to the number of visible images, which can be more than the number of different images.

Let’s see how to verify the visible images:

@Test
public void whenHas2VisibleImages_thenSuccess() {
    String filename = getFilePath("with_images.pdf");
    AssertThat.document(filename)
      .hasNumberOfVisibleImages(2);
}

PDFUnit is powerful enough to compare the content of images byte-by-byte. This also means that the image in the PDF and the reference image must be exactly equal.

Because of byte comparison, different format of images like BMP and PNG are considered unequal:

@Test
public void whenImageIsOnAnyPage_thenSuccess() {
    String filename = getFilePath("with_images.pdf");
    String imageFile = getFilePath("Superman.png");

    AssertThat.document(filename)
      .restrictedTo(AnyPage.getPreparedInstance())
      .hasImage()
      .matching(imageFile);
}

Notice the use of AnyPage here. We are not restricting the occurrence of the image to any particular page, rather on any page in the entire document.

The image to compare can take the form of BufferedImage, File, InputStream, or URL apart from the String that represents the file name.

8. Embedded Files

Certain PDF documents come with embedded files or attachments. It is necessary to test those as well:

@Test
public void whenHasEmbeddedFile_thenSuccess() {
    String filename = getFilePath("with_attachments.pdf");
 
    AssertThat.document(filename)
      .hasEmbeddedFile();
}

This will verify if the document under test has at least one embedded file.

We can verify the name of the embedded file as well:

@Test
public void whenHasmultipleEmbeddedFiles_thenSuccess() {
    String filename = getFilePath("with_attachments.pdf");

    AssertThat.document(filename)
      .hasNumberOfEmbeddedFiles(4)
      .hasEmbeddedFile()
      .withName("complaintform1.xls")
      .hasEmbeddedFile()
      .withName("complaintform2.xls")
      .hasEmbeddedFile()
      .withName("complaintform3.xls");
}

We can move one step further and verify the content of the embedded files as well:

@Test
public void whenEmbeddedFileContentMatches_thenSuccess() {
    String filename = getFilePath("with_attachments.pdf");
    String embeddedFileName = getFilePath("complaintform1.xls");

    AssertThat.document(filename)
      .hasEmbeddedFile()
      .withContent(embeddedFileName);
}

All the examples in this section are relatively straightforward and self-explanatory.

9. Conclusion

In this tutorial, we’ve seen several examples that cover the most common use cases related to PDF testing.

However, there is a lot more PDFUnit can do; make sure to visit the documentation page to learn more.


Viewing all articles
Browse latest Browse all 4537

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>