4.10.  Comparing Layout as Rendered Pages

PDF documents can be compared as rendered images (PNG) to ensure that a test document and a referenced document have the same layout.

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

You can select individual pages in many ways. All possibilities are described in chapter 13.2: “Page Selection”.

You can compare the layout of entire pages or you can restrict the comparison to sections of a page:

@Test
public void haveSameAppearanceInPageRegion() throws Exception {
  String filenameTest = "documentUnderTest.pdf";
  String filenameReference = "reference.pdf";
  
  int leftX  =   0;
  int upperY =   0;
  int width  = 210;
  int height =  50; 
  PageRegion pageRegion = new PageRegion(leftX, upperY, width, height);

  AssertThat.document(filenameTest)
            .and(filenameMaster)
            .restrictedTo(EVERY_PAGE)
            .restrictedTo(pageRegion)
            .haveSameAppearance()
  ;
}

In case of a test error, PDFUnit creates a diff image.

The diff image contains the name of the test in the header. And the name of the diff image is shown in the error message. That allows a cross reference between test and diff image.

The name of the diff-image file has following parts:

The folder for the diff-images can be defined using the key output.path.diffimages in the config file pdfunit.config.

If you need to analyze the layout of two PDF documents after a test fails, you can use the very powerful program DiffPDF. Information about this Open-Source application by Mark Summerfield is available on the project site http://soft.rubypdf.com/software/diffpdf. You can install the program under Linux with a package manager, for example apt-get install diffpdf. On Windows you can use it as a 'portable application' available from http://portableapps.com/apps/utilities/diffpdf_portable.