Why chai-pdf?

Have you ever been in a situation where your project requires you to validate pdf files? Do you want a simple way to verify them? If so, then read on.

Typically, we do these pdf tests manually as automating them can be complicated or costly. Some DIY approaches I’ve seen is to convert them into readable texts and then verify the existence of specific strings. However, I personally prefer the approach where you convert the pdf pages into images and do image comparison. This way, you verify both the presence of the texts you want to test but also the structure of the pdf itself. Killing two birds with one stone.

obligatory meme

chai-pdf provides such functionality packaged in a simple and easy to use chai plugin to validate pdfs using your existing NodeJS test frameworks.

Show me the code already!

sample chai-pdf test

Setup

First, you need to install the following System dependencies:

Once these dependencies are installed, you may now install the chai plugin to your project

npm install chai-pdf

In your NodeJS test framework create the following folder structure where you will place the pdfs:

/data/actualPdfs

/data/baselinePdfs

Test Execution

sample images of actual, baseline and diff

When you execute the tests, in the background, chai-pdf will convert each pdf into png files where each page will have its own index. Once the tests are done, if there are differences a diff image will be saved inside the data folder and will highlight the differences in Red.

Masking

masking

In some cases, the pdf file may contain dynamic data. It could be unique identifiers or dates. In this situation, chai-pdf allows you to pass options where you can indicate masking coordinates. This will draw a black rectangle to both the actual and baseline converted images before comparison.

What’s next?

So that’s it, easy-peasy.

I am thinking of implementing other features and configuration for this plugin. If you have some suggestions, let me know your thoughts in the comments section.

Stay awesome, and see you in the next one!

marcDacz