pdf-visual-compare 3.3.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,201 +1,21 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Igor Magdich
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,45 +1,169 @@
1
1
  # pdf-visual-compare
2
2
 
3
- Visual regression testing library for PDFs in JavaScript/TypeScript without binary and OS dependencies.
3
+ <p align="center">
4
+ <strong>Visual regression testing library for PDFs in JavaScript/TypeScript without binary or OS dependencies</strong>
5
+ </p>
4
6
 
5
- [![Tests on push](https://github.com/dichovsky/pdf-visual-compare/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/dichovsky/pdf-visual-compare/actions/workflows/test.yml)
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/pdf-visual-compare">
9
+ <img src="https://img.shields.io/npm/v/pdf-visual-compare.svg?style=flat-square" alt="npm version">
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/pdf-visual-compare">
12
+ <img src="https://img.shields.io/npm/dm/pdf-visual-compare.svg?style=flat-square" alt="npm downloads">
13
+ </a>
14
+ <a href="https://github.com/dichovsky/pdf-visual-compare/actions/workflows/test.yml">
15
+ <img src="https://github.com/dichovsky/pdf-visual-compare/actions/workflows/test.yml/badge.svg?branch=main" alt="Tests">
16
+ </a>
17
+ <a href="https://github.com/dichovsky/pdf-visual-compare/blob/main/LICENSE">
18
+ <img src="https://img.shields.io/github/license/dichovsky/pdf-visual-compare?style=flat-square" alt="License">
19
+ </a>
20
+ </p>
6
21
 
7
- ## Getting Started
22
+ ---
8
23
 
9
- ### Installation
24
+ ## Table of Contents
25
+
26
+ - [Requirements](#requirements)
27
+ - [Installation](#installation)
28
+ - [Usage](#usage)
29
+ - [Basic comparison](#basic-comparison)
30
+ - [Comparison with options](#comparison-with-options)
31
+ - [Comparing PDF buffers](#comparing-pdf-buffers)
32
+ - [API](#api)
33
+ - [comparePdf](#comparepdfactualpdf-expectedpdf-options)
34
+ - [ComparePdfOptions](#comparepdfoptions)
35
+ - [ExcludedPageArea](#excludedpagearea)
36
+ - [Support](#support)
37
+
38
+ ---
39
+
40
+ ## Requirements
41
+
42
+ - Node.js >= 20
43
+
44
+ ---
45
+
46
+ ## Installation
10
47
 
11
48
  ```sh
12
49
  npm install -D pdf-visual-compare
13
50
  ```
14
51
 
15
- ### Example
52
+ ---
53
+
54
+ ## Usage
55
+
56
+ ### Basic comparison
57
+
58
+ ```typescript
59
+ import { comparePdf } from 'pdf-visual-compare';
60
+
61
+ const isEqual = await comparePdf('./actual.pdf', './expected.pdf');
62
+ // true → PDFs are visually identical
63
+ // false → PDFs differ
64
+ ```
65
+
66
+ ### Comparison with options
16
67
 
17
- ```javascript
18
- const result = await comparePdf('./pdf1.pdf', './pdf2.pdf');
68
+ ```typescript
69
+ import { comparePdf } from 'pdf-visual-compare';
19
70
 
20
- // If you want to configure the comparing process, use the following options
71
+ const isEqual = await comparePdf('./actual.pdf', './expected.pdf', {
72
+ // Folder for diff PNG images written when differences are found. Default: ./comparePdfOutput
73
+ diffsOutputFolder: 'test-results/diffs',
74
+
75
+ // Maximum number of differing pixels allowed before the comparison fails.
76
+ // 0 = pixel-perfect match required (default). Must be >= 0.
77
+ compareThreshold: 200,
78
+
79
+ // Per-page exclusion zones, matched by the `pageNumber` field (1-based).
80
+ // `pageNumber: 1` → first page, `pageNumber: 2` → second page, etc.
81
+ // Pixel coordinates are relative to the rendered PNG at the configured viewportScale.
82
+ excludedAreas: [
83
+ {
84
+ pageNumber: 1,
85
+ excludedAreas: [
86
+ { x1: 700, y1: 375, x2: 790, y2: 400 }, // dynamic timestamp on page 1
87
+ ],
88
+ },
89
+ {
90
+ pageNumber: 2,
91
+ excludedAreas: [
92
+ { x1: 680, y1: 240, x2: 955, y2: 465 }, // chart on page 2
93
+ ],
94
+ },
95
+ ],
21
96
 
22
- const result = await comparePdf('./pdf1.pdf', './pdf2.pdf', {
23
- diffsOutputFolder: 'diffs', // Folder to write output PNG files with differences
24
97
  pdfToPngConvertOptions: {
25
- viewportScale: 2.0, // The desired scale of PNG viewport. Default value is 2.0.
26
- disableFontFace: false, // When `false`, fonts will be rendered using a built-in font renderer that constructs the glyphs with primitive path commands. Default value is true.
27
- useSystemFonts: false, // When `true`, fonts that aren't embedded in the PDF document will fallback to a system font. Default value is false.
28
- pdfFilePassword: 'pa$$word', // Password for encrypted PDF.
29
- outputFolder: 'output/folder', // Folder to write output PNG files. If not specified, PNG output will be available only as a Buffer content, without saving to a file.
30
- outputFileMask: 'buffer', // Output filename mask. Default value is 'buffer'.
31
- pagesToProcess: [1, 3, 11], // Subset of pages to convert (first page = 1), other pages will be skipped if specified.
32
- strictPagesToProcess: false, // When `true`, will throw an error if specified page number in pagesToProcess is invalid, otherwise will skip invalid page. Default value is false.
33
- verbosityLevel: 0 // Verbosity level. ERRORS: 0, WARNINGS: 1, INFOS: 5. Default value is 0.
98
+ viewportScale: 2.0, // Rendering scale higher means more detail. Default: 2.0.
99
+ disableFontFace: true, // Use built-in font renderer. Default: true.
100
+ useSystemFonts: false, // Fall back to system fonts for non-embedded fonts. Default: false.
101
+ enableXfa: false, // Enable XFA form rendering. Default: false.
102
+ pdfFilePassword: 'pa$$word', // Password for encrypted PDFs.
103
+ outputFolder: 'output/pngs', // Save intermediate PNG files here. Omit to keep in memory only.
104
+ outputFileMaskFunc: (pageNumber) => `page_${pageNumber}.png`, // Custom PNG filename.
105
+ pagesToProcess: [1, 3], // Limit comparison to specific pages (1-based). Default: all pages.
106
+ verbosityLevel: 0, // 0 = errors only, 1 = warnings, 5 = info. Default: 0.
34
107
  },
35
- excludedAreas: [], // Areas list to exclude from comparing for each PDF page. Empty array by default.
36
- compareThreshold: 0.1 // Comparing threshold, ranges from 0 to 1. Smaller values make the comparison more sensitive. 0.1 by default.
37
108
  });
38
109
  ```
39
110
 
111
+ ### Comparing PDF buffers
112
+
113
+ Both file paths and `Buffer` instances are accepted as inputs:
114
+
115
+ ```typescript
116
+ import { readFileSync } from 'node:fs';
117
+ import { comparePdf } from 'pdf-visual-compare';
118
+
119
+ const actual = readFileSync('./actual.pdf');
120
+ const expected = readFileSync('./expected.pdf');
121
+
122
+ const isEqual = await comparePdf(actual, expected);
123
+ ```
124
+
125
+ ---
126
+
127
+ ## API
128
+
129
+ ### `comparePdf(actualPdf, expectedPdf, options?)`
130
+
131
+ | Parameter | Type | Description |
132
+ | ------------- | ------------------------------------------- | ----------------------------------------- |
133
+ | `actualPdf` | `string \| Buffer \| ArrayBufferLike` | File path or buffer of the PDF under test |
134
+ | `expectedPdf` | `string \| Buffer \| ArrayBufferLike` | File path or buffer of the reference PDF |
135
+ | `options` | `ComparePdfOptions` _(optional)_ | Comparison configuration |
136
+
137
+ Returns `Promise<boolean>` — `true` if the PDFs are visually equivalent within the configured threshold, `false` otherwise.
138
+
139
+ **Throws:**
140
+ - `Error: PDF file not found: <path>` — when a string argument points to a non-existent file.
141
+ - `Error: Unknown input file type.` — when an argument is neither a string nor a Buffer.
142
+ - `Error: Compare Threshold cannot be less than 0.` — when `options.compareThreshold < 0`.
143
+
144
+ ### `ComparePdfOptions`
145
+
146
+ | Property | Type | Default | Description |
147
+ | ------------------------ | --------------------- | -------------------- | --------------------------------------------------------------------------- |
148
+ | `diffsOutputFolder` | `string` | `./comparePdfOutput` | Folder where diff PNG images are written |
149
+ | `compareThreshold` | `number` | `0` | Maximum number of differing pixels allowed before comparison fails |
150
+ | `excludedAreas` | `ExcludedPageArea[]` | `[]` | Per-page exclusion zones matched by the `pageNumber` field of each entry (1-based) |
151
+ | `pdfToPngConvertOptions` | `PdfToPngOptions` | see below | Options forwarded to [`pdf-to-png-converter`](https://github.com/dichovsky/pdf-to-png-converter) |
152
+
153
+ ### `ExcludedPageArea`
154
+
155
+ | Property | Type | Description |
156
+ | ------------------- | -------- | --------------------------------------------------------------------------------------------------- |
157
+ | `pageNumber` | `number` | 1-based page number this exclusion applies to (`1` = first page, `2` = second page, etc.) |
158
+ | `excludedAreas` | `Area[]` | Rectangles to exclude. `Area` = `{ x1, y1, x2, y2 }` in pixels at the configured `viewportScale` |
159
+ | `excludedAreaColor` | `Color` | Fill color for excluded regions in diff images. `Color` = `{ r, g, b }` with values 0–255 |
160
+ | `diffFilePath` | `string` | Override the diff image output path for this page |
161
+ | `matchingThreshold` | `number` | Per-page pixel threshold, overrides the document-level `compareThreshold` for this page |
162
+
163
+ ---
164
+
40
165
  ## Support
41
166
 
42
167
  If you want to support my work, you can buy me a coffee.
43
168
 
44
169
  [![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://buymeacoffee.com/dichovsky)
45
-
package/out/comparePdf.js CHANGED
@@ -27,50 +27,58 @@ async function comparePdf(actualPdf, expectedPdf, opts = {}) {
27
27
  if (!pdfToPngConvertOpts.outputFileMaskFunc) {
28
28
  pdfToPngConvertOpts.outputFileMaskFunc = (pageNumber) => `comparePdf_${pageNumber}.png`;
29
29
  }
30
- const diffsOutputFolder = opts?.diffsOutputFolder ?? const_js_1.DEFAULT_DIFFS_FOLDER;
31
- const compareThreshold = opts?.compareThreshold ?? 0;
32
- const excludedAreas = opts?.excludedAreas ?? [];
30
+ const diffsOutputFolder = opts.diffsOutputFolder ?? const_js_1.DEFAULT_DIFFS_FOLDER;
31
+ const compareThreshold = opts.compareThreshold ?? 0;
32
+ const excludedAreas = opts.excludedAreas ?? [];
33
33
  if (compareThreshold < 0) {
34
34
  throw Error('Compare Threshold cannot be less than 0.');
35
35
  }
36
- // Convert PDFs to PNGs
37
- let [actualPdfPngPages, expectedPdfPngPages] = await Promise.all([
38
- (0, pdf_to_png_converter_1.pdfToPng)(actualPdf, pdfToPngConvertOpts),
39
- (0, pdf_to_png_converter_1.pdfToPng)(expectedPdf, pdfToPngConvertOpts),
40
- ]);
41
- // Ensure actualPdfPngPages is always the longer array to avoid index out of bounds errors
42
- if (actualPdfPngPages.length < expectedPdfPngPages.length) {
43
- [actualPdfPngPages, expectedPdfPngPages] = [expectedPdfPngPages, actualPdfPngPages];
44
- }
36
+ // Convert PDFs to PNGs sequentially to avoid PDF.js worker state corruption.
37
+ // When two pdfToPng calls run concurrently via Promise.all, the pdfDocument.cleanup()
38
+ // in one call can corrupt the shared PDF.js worker state for the other call, causing
39
+ // "Invalid page request" errors — particularly when the two PDFs have different page counts.
40
+ const actualPdfPngPages = await (0, pdf_to_png_converter_1.pdfToPng)(actualPdf, { ...pdfToPngConvertOpts });
41
+ const expectedPdfPngPages = await (0, pdf_to_png_converter_1.pdfToPng)(expectedPdf, { ...pdfToPngConvertOpts });
45
42
  let documentCompareResult = true;
46
- actualPdfPngPages.forEach((pngPage, index) => {
43
+ for (const [index, pngPage] of actualPdfPngPages.entries()) {
44
+ // Look up the exclusion zone for this page by 1-based page number.
45
+ const pageExcludedArea = excludedAreas.find((area) => area.pageNumber === index + 1);
46
+ if (!pngPage.content) {
47
+ throw new Error(`Page content is undefined for page: ${pngPage.name}`);
48
+ }
49
+ // Only forward the fields that ComparePngOptions actually recognises.
50
+ // The per-page diffFilePath override takes precedence over the auto-generated path.
47
51
  const comparePngOpts = {
48
- ...opts?.pdfToPngConvertOptions,
49
- ...excludedAreas[index],
52
+ excludedAreas: pageExcludedArea?.excludedAreas,
53
+ diffFilePath: pageExcludedArea?.diffFilePath ?? (0, node_path_1.resolve)(diffsOutputFolder, `diff_${pngPage.name}`),
50
54
  throwErrorOnInvalidInputData: false,
51
55
  };
52
- comparePngOpts.diffFilePath = (0, node_path_1.resolve)(diffsOutputFolder, `diff_${pngPage.name}`);
53
56
  const pngPageOutputToCompareWith = expectedPdfPngPages.find((p) => p.name === pngPage.name);
54
57
  const pageCompareResult = (0, png_visual_compare_1.comparePng)(pngPage.content, pngPageOutputToCompareWith?.content ?? '', comparePngOpts);
55
- if (pageCompareResult > compareThreshold) {
58
+ // Per-page matchingThreshold overrides the document-level compareThreshold when set.
59
+ const pageThreshold = pageExcludedArea?.matchingThreshold ?? compareThreshold;
60
+ if (pageCompareResult > pageThreshold) {
56
61
  documentCompareResult = false;
57
62
  }
58
- });
63
+ }
64
+ // Extra pages present in expected but absent from actual are always a mismatch.
65
+ if (expectedPdfPngPages.length > actualPdfPngPages.length) {
66
+ documentCompareResult = false;
67
+ }
59
68
  return documentCompareResult;
60
69
  }
61
70
  /**
62
- * Validates the type of the input file. The input file can either be a Buffer or a string representing a file path.
63
- * If the input file is a Buffer, the function returns without any error.
64
- * If the input file is a string, the function checks if the file exists at the given path.
65
- * If the file does not exist, an error is thrown.
66
- * If the input file is neither a Buffer nor a string, an error is thrown.
71
+ * Validates the type of the input file.
72
+ *
73
+ * Accepts a `Buffer`, any `ArrayBufferLike` (`ArrayBuffer` / `SharedArrayBuffer`), or a
74
+ * string path that points to an existing file. Throws for any other input.
67
75
  *
68
- * @param inputFile - The input file to validate. It can be a Buffer or a string representing a file path.
69
- * @throws {Error} If the input file is a string and the file does not exist.
70
- * @throws {Error} If the input file is neither a Buffer nor a string.
76
+ * @param inputFile - The input to validate.
77
+ * @throws {Error} If the input is a string path that does not exist.
78
+ * @throws {Error} If the input is neither a recognised buffer type nor a string.
71
79
  */
72
80
  function validateInputFileType(inputFile) {
73
- if (Buffer.isBuffer(inputFile)) {
81
+ if (Buffer.isBuffer(inputFile) || inputFile instanceof ArrayBuffer || inputFile instanceof SharedArrayBuffer) {
74
82
  return;
75
83
  }
76
84
  if (typeof inputFile === 'string') {
package/out/const.d.ts CHANGED
@@ -1 +1,2 @@
1
+ /** Default folder path for diff PNG images produced during PDF comparison. */
1
2
  export declare const DEFAULT_DIFFS_FOLDER: string;
package/out/const.js CHANGED
@@ -2,4 +2,5 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DEFAULT_DIFFS_FOLDER = void 0;
4
4
  const node_path_1 = require("node:path");
5
+ /** Default folder path for diff PNG images produced during PDF comparison. */
5
6
  exports.DEFAULT_DIFFS_FOLDER = (0, node_path_1.resolve)(`./comparePdfOutput`);
package/out/index.d.ts CHANGED
@@ -1,3 +1,12 @@
1
+ /**
2
+ * pdf-visual-compare
3
+ *
4
+ * Visual regression testing library for PDFs in JavaScript/TypeScript.
5
+ * Converts PDF pages to PNG images and performs pixel-level comparison,
6
+ * requiring no native binaries or OS-level dependencies.
7
+ *
8
+ * @module pdf-visual-compare
9
+ */
1
10
  export { comparePdf } from './comparePdf.js';
2
11
  export type { ComparePdfOptions } from './types/ComparePdfOptions.js';
3
12
  export type { ExcludedPageArea } from './types/ExcludedPageArea.js';
package/out/index.js CHANGED
@@ -1,5 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.comparePdf = void 0;
4
+ /**
5
+ * pdf-visual-compare
6
+ *
7
+ * Visual regression testing library for PDFs in JavaScript/TypeScript.
8
+ * Converts PDF pages to PNG images and performs pixel-level comparison,
9
+ * requiring no native binaries or OS-level dependencies.
10
+ *
11
+ * @module pdf-visual-compare
12
+ */
4
13
  var comparePdf_js_1 = require("./comparePdf.js");
5
14
  Object.defineProperty(exports, "comparePdf", { enumerable: true, get: function () { return comparePdf_js_1.comparePdf; } });
@@ -1,8 +1,30 @@
1
1
  import type { PdfToPngOptions } from 'pdf-to-png-converter';
2
2
  import type { ExcludedPageArea } from './ExcludedPageArea.js';
3
+ /**
4
+ * Options for configuring the PDF comparison process.
5
+ */
3
6
  export type ComparePdfOptions = {
7
+ /**
8
+ * Folder path where diff PNG images are written when differences are found.
9
+ * @default "./comparePdfOutput"
10
+ */
4
11
  diffsOutputFolder?: string;
12
+ /**
13
+ * Options passed to the underlying PDF-to-PNG converter.
14
+ * Controls rendering scale, font handling, page selection, and more.
15
+ */
5
16
  pdfToPngConvertOptions?: PdfToPngOptions;
17
+ /**
18
+ * Per-page areas to exclude from pixel comparison, matched by array index (0-based).
19
+ * The element at index 0 applies to the first page, index 1 to the second, and so on.
20
+ * @default []
21
+ */
6
22
  excludedAreas?: readonly ExcludedPageArea[];
23
+ /**
24
+ * Maximum number of differing pixels allowed before the comparison is considered a failure.
25
+ * A value of `0` requires a pixel-perfect match. Must be >= 0.
26
+ * @default 0
27
+ * @throws {Error} When set to a value less than 0.
28
+ */
7
29
  compareThreshold?: number;
8
30
  };
@@ -1,8 +1,42 @@
1
1
  import type { Area, Color } from 'png-visual-compare';
2
+ /**
3
+ * Defines a page-specific exclusion zone for PDF comparison.
4
+ *
5
+ * Each entry is matched to a PDF page by its `pageNumber` field (1-based):
6
+ * `pageNumber: 1` targets the first page, `pageNumber: 2` the second, and so on.
7
+ * Entries whose `pageNumber` does not correspond to any page are silently ignored.
8
+ */
2
9
  export type ExcludedPageArea = {
10
+ /**
11
+ * 1-based page number this exclusion applies to.
12
+ * Must match the page's position in the PDF (`1` = first page, `2` = second page, etc.).
13
+ */
3
14
  pageNumber: number;
15
+ /**
16
+ * Rectangular regions to exclude from pixel comparison on this page.
17
+ * Coordinates (`x1`, `y1`, `x2`, `y2`) are in pixels relative to the rendered PNG
18
+ * at the configured `viewportScale`. `(x1, y1)` is the top-left corner and
19
+ * `(x2, y2)` is the bottom-right corner.
20
+ */
4
21
  excludedAreas?: Area[];
22
+ /**
23
+ * Fill color used to paint excluded regions in the diff output image.
24
+ * Expressed as `{ r, g, b }` with channel values in the range 0–255.
25
+ *
26
+ * @remarks Currently reserved for future use. The underlying `png-visual-compare`
27
+ * library always paints excluded areas blue; this field has no effect at runtime.
28
+ */
5
29
  excludedAreaColor?: Color;
30
+ /**
31
+ * Override the diff image output file path for this specific page.
32
+ * When set, takes precedence over the path derived from `diffsOutputFolder`.
33
+ * When omitted, the path is auto-generated as `<diffsOutputFolder>/diff_<pageName>`.
34
+ */
6
35
  diffFilePath?: string;
36
+ /**
37
+ * Per-page pixel difference threshold that overrides the document-level
38
+ * `compareThreshold` for this page only. Must be >= 0.
39
+ * When omitted, the document-level `compareThreshold` applies.
40
+ */
7
41
  matchingThreshold?: number;
8
42
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pdf-visual-compare",
3
- "version": "3.3.0",
3
+ "version": "3.5.0",
4
4
  "description": "Visual regression testing library for PDFs in Js/Ts without binary and OS dependencies.",
5
5
  "keywords": [
6
6
  "pdf",
@@ -9,7 +9,9 @@
9
9
  "pdf compare",
10
10
  "compare pdf",
11
11
  "pdf diff",
12
- "visual regression"
12
+ "visual regression",
13
+ "pdf testing",
14
+ "visual-diff"
13
15
  ],
14
16
  "homepage": "https://github.com/dichovsky/pdf-visual-compare#readme",
15
17
  "bugs": {
@@ -19,14 +21,26 @@
19
21
  "type": "git",
20
22
  "url": "git+https://github.com/dichovsky/pdf-visual-compare.git"
21
23
  },
24
+ "funding": {
25
+ "type": "buymeacoffee",
26
+ "url": "https://buymeacoffee.com/dichovsky"
27
+ },
22
28
  "license": "MIT",
23
29
  "author": "Igor Magdich <magdich.igor@gmail.com>",
24
30
  "main": "./out/index.js",
25
31
  "types": "./out/index.d.ts",
32
+ "exports": {
33
+ ".": {
34
+ "require": "./out/index.js",
35
+ "types": "./out/index.d.ts",
36
+ "default": "./out/index.js"
37
+ }
38
+ },
26
39
  "files": [
27
40
  "./out"
28
41
  ],
29
42
  "scripts": {
43
+ "prepublishOnly": "npm test && npm run build",
30
44
  "prebuild": "npm run clean",
31
45
  "build": "tsc --pretty",
32
46
  "clean": "rimraf ./out ./coverage ./test-results ./comparePdfOutput",
@@ -34,31 +48,29 @@
34
48
  "predocker:run": "npm run clean",
35
49
  "docker:run": "docker run --rm -it -v $PWD/test-results:/usr/pkg/test-results test-pdf-visual-compare",
36
50
  "docker:test": "vitest run",
37
- "test:license": "npx --yes license-checker --production --onlyAllow \"ISC; MIT; MIT OR X11; BSD; Apache-2.0; Unlicense\"",
38
51
  "lint": "eslint .",
39
52
  "lint:fix": "npm run lint -- --fix",
40
53
  "pretest": "npm run clean && npm run lint && npm run test:license && npm run build",
41
54
  "test": "vitest run --coverage",
42
- "test:docker": "npm run docker:build && npm run docker:run"
55
+ "test:docker": "npm run docker:build && npm run docker:run",
56
+ "test:license": "npx --yes license-checker --production --onlyAllow \"ISC; MIT; MIT OR X11; BSD; Apache-2.0; Unlicense\""
43
57
  },
44
58
  "dependencies": {
45
- "pdf-to-png-converter": "~3.11.0",
46
- "png-visual-compare": "~3.2.0"
59
+ "pdf-to-png-converter": "~3.18.0",
60
+ "png-visual-compare": "~5.1.0"
47
61
  },
48
62
  "devDependencies": {
49
- "@types/node": "^24.10.0",
63
+ "@types/node": "^25.6.0",
50
64
  "@types/pngjs": "^6.0.5",
51
- "@typescript-eslint/eslint-plugin": "^8.46.3",
52
- "@typescript-eslint/parser": "^8.46.3",
53
- "@vitest/coverage-v8": "^4.0.7",
54
- "eslint": "^9.39.1",
55
- "rimraf": "^6.1.0",
56
- "ts-node": "^10.9.2",
57
- "typescript": "^5.9.3",
58
- "vitest": "^4.0.7"
65
+ "@vitest/coverage-v8": "^4.1.4",
66
+ "eslint": "^10.2.0",
67
+ "jiti": "^2.6.1",
68
+ "rimraf": "^6.1.3",
69
+ "typescript": "^6.0.2",
70
+ "typescript-eslint": "^8.58.1",
71
+ "vitest": "^4.1.4"
59
72
  },
60
73
  "engines": {
61
- "node": ">=20",
62
- "yarn": "please-use-npm"
74
+ "node": ">=20"
63
75
  }
64
- }
76
+ }