4.8.  Comparing Images

Quantity

The first test compares the number of images in two PDF documents:

@Test
public void haveSameNumberOfImages() throws Exception {
  String filenameTest = "documentUnderTest.pdf";
  String filenameReference = "reference.pdf";
  
  AssertThat.document(filenameTest)
            .and(filenameReference) 
            .haveSameNumberOfImages()
  ;
}

The comparison can be limited to selected pages:

@Test
public void haveSameNumberOfImages_OnPage2() throws Exception {
  String filenameTest = "documentUnderTest.pdf";
  String filenameReference = "reference.pdf";
  PagesToUse page2 = PagesToUse.getPage(2);
  
  AssertThat.document(filenameTest)
            .and(filenameReference) 
            .restrictedTo(page2)
            .haveSameNumberOfImages()
  ;
}

All possibilities to select pages are described in chapter 13.2: “Page Selection”.

Content of Images

The images stored in a test PDF can be compared with those of a reference PDF. They are identified as equal when they are equal byte-by-byte.

/**
 * The method haveSameImages() does not consider the order of the images.
 */
@Test
public void haveSameImages() throws Exception {
  String filenameTest = "documentUnderTest.pdf";
  String filenameReference = "reference.pdf";
  
  AssertThat.document(filenameTest)
            .and(filenameReference) 
            .haveSameImages()
  ;
}

This test method does not care about which pages the images appear on or how often they are used.

You can restrict the comparison of reference to individual pages:

@Test
public void haveSameImages_OnPage2() throws Exception {
  String filenameTest = "documentUnderTest.pdf";
  String filenameReference = "reference.pdf";
  PagesToUse page2 = PagesToUse.getPage(2);
  
  AssertThat.document(filenameTest)
            .and(filenameReference)
            .restrictedTo(page2)          
            .haveSameImages()            1
  ;
}
@Test
public void haveSameImages_BeforePage2() throws Exception {
  String filenameTest = "documentUnderTest.pdf";
  String filenameReference = "reference.pdf";
  PagesToUse pagesBefore2 = ON_EVERY_PAGE.before(2);
  
  AssertThat.document(filenameTest)
            .and(filenameReference) 
            .restrictedTo(pagesBefore2)  
            .haveSameImages()            1
  ;
}

1 1

The order of images is irrelevant for the comparison.

If there are any doubts about the images in a PDF document all images can be extracted using the utility ExtractImages. See chapter 9.7: “Extract Images from PDF”.