npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

pdf-visual-diff

v0.14.0

Published

Visual Regression Testing for PDFs in JavaScript

Downloads

24,314

Readme

Test Visual Regression in PDFs

NPM version code style: prettier Pull Request CI/CD

pdf-visual-diff is a library for testing visual regressions in PDFs. It uses pdf.js to convert PDFs into PNGs and jimp for image comparisons.

API Documentation

Installation

npm install -D pdf-visual-diff

Description

This package exports comparePdfToSnapshot function, with the following signature:

function comparePdfToSnapshot(
  pdf: string | Buffer,
  snapshotDir: string,
  snapshotName: string,
  options?: CompareOptions
): Promise<boolean>

Compares a PDF to a persisted snapshot, with behavior for handling missing snapshots controlled by the failOnMissingSnapshot option.

The function has the following side effects:

  • If no snapshot exists:
    • If failOnMissingSnapshot is false (default), the PDF is converted to an image, saved as a new snapshot, and the function returns true.
    • If failOnMissingSnapshot is true, the function returns false without creating a new snapshot.
  • If a snapshot exists, the PDF is converted to an image and compared to the snapshot:
    • If they differ, the function returns false and creates two additional images next to the snapshot: one with the suffix new (the current view of the PDF as an image) and one with the suffix diff (showing the difference between the snapshot and the new image).
    • If they are equal, the function returns true. If new and diff versions are present, they are deleted.

Returns a promise that resolves to true if the PDF matches the snapshot or if the behavior for a missing snapshot is configured to allow it. Returns false if the PDF differs from the snapshot or if failOnMissingSnapshot is true and the snapshot is missing.

For further details and configuration options, please refer to the API Documentation.

Sample usage

Note: You can find sample projects in the examples folder.

Write a test file:

import { comparePdfToSnapshot } from 'pdf-visual-diff'
import { expect } from 'chai'

describe('test PDF report visual regression', () => {
  const pathToPdf = 'path to your PDF' // or you might pass a Buffer instead
  it('should pass', () =>
    comparePdfToSnapshot(pathToPdf, __dirname, 'my-awesome-report').then(
      (x) => expect(x).to.be.true,
    ))
})

// Example with masking regions of a two-page PDF
describe('PDF masking', () => {
  it('should mask two-page PDF', () => {
    const blueMask: RegionMask = {
      type: 'rectangle-mask',
      x: 50,
      y: 75,
      width: 140,
      height: 100,
      color: 'Blue',
    }
    const greenMask: RegionMask = {
      type: 'rectangle-mask',
      x: 110,
      y: 200,
      width: 90,
      height: 50,
      color: 'Green',
    }

    comparePdfToSnapshot(twoPagePdfPath, __dirname, 'different-mask-per-page', {
      maskRegions: (page) => {
        switch (page) {
          case 1:
            return [blueMask]
          case 2:
            return [greenMask]
          default:
            return []
        }
      },
    }).then((x) => expect(x).to.be.true))
  })
})

Tools

pdf-visual-diff provides a CLI for approving or discarding new PDF snapshots. The CLI can be used via npx or npm by updating the scripts section of your package.json:

"scripts": {
  "test:pdf-approve": "pdf-visual-diff approve",
  "test:pdf-discard": "pdf-visual-diff discard"
}

To approve new snapshots, run the following command in your terminal:

npm run test:pdf-approve

Paths for the new snapshots will be listed. You will then be prompted to confirm whether you want to replace the old snapshots with the new ones:

New snapshots:
./__snapshots__/test_doc_1.new.png
./__snapshots__/single-page-snapshot.new.png
Are you sure you want to overwrite current snapshots? [Y/n]:

These commands can be customized by specifying a custom path and snapshots folder name.

Approve command help:

npx pdf-visual-diff approve --help

Approve new snapshots

Options:
      --help                Show help                                  [boolean]
      --version             Show version number                        [boolean]
  -p, --path                                                      [default: "."]
  -s, --snapshots-dir-name                            [default: "__snapshots__"]

Discard command help:

npx pdf-visual-diff discard --help

Discard new snapshots and diffs

Options:
      --help                Show help                                  [boolean]
      --version             Show version number                        [boolean]
  -p, --path                                                      [default: "."]
  -s, --snapshots-dir-name                            [default: "__snapshots__"]

Usage with Jest

This packages provides a custom Jest matcher toMatchPdfSnapshot.

Setup

"jest": {
  "setupFilesAfterEnv": ["pdf-visual-diff/lib/toMatchPdfSnapshot"]
}

If you are using TypeScript add import('pdf-visual-diff/lib/toMatchPdfSnapshot') to your typings.

Usage

In your tests, pass a path to the PDF or PDF content a Buffer.

const pathToPdf = 'path to your PDF' // or you might pass a Buffer instead
describe('test PDF report visual regression', () => {
  it('should match', () => expect(pathToPdf).toMatchPdfSnapshot())
})

As you can see, there is no need to manage directories or names manually. The necessary information is extracted from the Jest context.