@patrickdk77/xfa-flatten 0.0.0-stage → 0.1.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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +14 -0
  4. package/README.md +112 -2
  5. package/dist/barcode-paint.d.ts +11 -0
  6. package/dist/barcode-paint.js +135 -0
  7. package/dist/barcode.d.ts +45 -0
  8. package/dist/barcode.js +750 -0
  9. package/dist/canvas.d.ts +59 -0
  10. package/dist/canvas.js +179 -0
  11. package/dist/cli.d.ts +2 -0
  12. package/dist/cli.js +34 -0
  13. package/dist/css.d.ts +48 -0
  14. package/dist/css.js +288 -0
  15. package/dist/deadline.d.ts +6 -0
  16. package/dist/deadline.js +18 -0
  17. package/dist/filters.d.ts +21 -0
  18. package/dist/filters.js +296 -0
  19. package/dist/flatten.d.ts +25 -0
  20. package/dist/flatten.js +319 -0
  21. package/dist/font-metrics.d.ts +9 -0
  22. package/dist/font-metrics.js +215 -0
  23. package/dist/fonts.d.ts +36 -0
  24. package/dist/fonts.js +144 -0
  25. package/dist/images.d.ts +23 -0
  26. package/dist/images.js +519 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.js +5 -0
  29. package/dist/index.mjs +3 -0
  30. package/dist/layout.d.ts +64 -0
  31. package/dist/layout.js +779 -0
  32. package/dist/limits.d.ts +2 -0
  33. package/dist/limits.js +6 -0
  34. package/dist/locale.d.ts +29 -0
  35. package/dist/locale.js +97 -0
  36. package/dist/paint.d.ts +15 -0
  37. package/dist/paint.js +533 -0
  38. package/dist/pdf-crypt.d.ts +35 -0
  39. package/dist/pdf-crypt.js +261 -0
  40. package/dist/pdf-read.d.ts +140 -0
  41. package/dist/pdf-read.js +1026 -0
  42. package/dist/pdf417-table.d.ts +2 -0
  43. package/dist/pdf417-table.js +146 -0
  44. package/dist/pdfjs-repair.d.ts +13 -0
  45. package/dist/pdfjs-repair.js +257 -0
  46. package/dist/pdfjs.d.ts +16 -0
  47. package/dist/pdfjs.js +62 -0
  48. package/dist/picture.d.ts +40 -0
  49. package/dist/picture.js +678 -0
  50. package/dist/saslprep.d.ts +11 -0
  51. package/dist/saslprep.js +178 -0
  52. package/dist/style.d.ts +29 -0
  53. package/dist/style.js +178 -0
  54. package/dist/text.d.ts +44 -0
  55. package/dist/text.js +199 -0
  56. package/dist/tiff.d.ts +3 -0
  57. package/dist/tiff.js +270 -0
  58. package/dist/tree.d.ts +23 -0
  59. package/dist/tree.js +54 -0
  60. package/dist/types.d.ts +31 -0
  61. package/dist/types.js +2 -0
  62. package/dist/writer.d.ts +38 -0
  63. package/dist/writer.js +145 -0
  64. package/dist/xfa-apply.d.ts +49 -0
  65. package/dist/xfa-apply.js +617 -0
  66. package/dist/xfa-model.d.ts +42 -0
  67. package/dist/xfa-model.js +227 -0
  68. package/dist/xfa-paint.d.ts +24 -0
  69. package/dist/xfa-paint.js +275 -0
  70. package/dist/xfa-spec.d.ts +47 -0
  71. package/dist/xfa-spec.js +3 -0
  72. package/dist/xml.d.ts +30 -0
  73. package/dist/xml.js +211 -0
  74. package/package.json +83 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 patrickdk77
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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,14 @@
1
+ xfa-flatten
2
+ Copyright (c) 2026 patrickdk77. Licensed under the MIT License; see LICENSE.
3
+
4
+ This package includes data from ZXing, licensed under the Apache License,
5
+ Version 2.0. The license text is in LICENSE-APACHE-2.0.
6
+
7
+ src/pdf417-table.ts holds the PDF417 bar and space patterns from ZXing's
8
+ encoder, core/src/main/java/com/google/zxing/pdf417/encoder/PDF417.java
9
+ (https://github.com/zxing/zxing). That file carries this notice:
10
+
11
+ Copyright 2006 Jeremias Maerki in part, and ZXing Authors in part
12
+
13
+ The patterns were changed from Java integer arrays to packed hex strings. The
14
+ values are the same.
package/README.md CHANGED
@@ -1,3 +1,113 @@
1
- # Temporary Holding Version
1
+ # xfa-flatten
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Some PDF forms built with Adobe LiveCycle Designer hold nothing but a dynamic XFA form. The catalog says `NeedsRendering`, and the one real page reads "Please wait...". Chrome, Edge and Preview show only that page. xfa-flatten turns such a file into a plain PDF that any reader shows. The form's pages become ordinary drawing operators and text, with the filled-in data. The output has no form fields, no XFA and no scripts.
4
+
5
+ It runs in plain Node with no browser and no canvas, so it fits in an AWS Lambda.
6
+
7
+ ## Requirements
8
+
9
+ Node 22.13.0 or later. That is the floor of pdfjs-dist, the one runtime dependency, which is higher than the Node 18 floor of the other defuse packages.
10
+
11
+ ## Usage
12
+
13
+ ```js
14
+ const { flattenXfa } = require('@patrickdk77/xfa-flatten');
15
+
16
+ const result = await flattenXfa(bytes, { deadline: Date.now() + 30_000 });
17
+ result.status; // 'flattened', 'unchanged' or 'failed'
18
+ result.bytes; // the new PDF, when flattened
19
+ result.pages; // its page count
20
+ result.notes; // [{ kind, location, detail }]
21
+ ```
22
+
23
+ ES modules work too: `import { flattenXfa } from '@patrickdk77/xfa-flatten'`.
24
+
25
+ `status` is `unchanged` when there is nothing to do. That covers a PDF with no XFA and a static XFA form, whose pages already carry their content. It is `failed` when pdf.js cannot open or lay out the form, or when the deadline passes. The first note then carries the reason, with pdf.js's own error text when there is one.
26
+
27
+ Run pdf-defuse over the output as over any upload. xfa-flatten does not depend on it.
28
+
29
+ ### Options
30
+
31
+ `password` is a string or an array of strings, taken as pdf-defuse takes it. Each one is tried in order, as the user password and then as the owner password, and the empty password comes last. An AES-256 (revision 6) password is prepared with SASLprep, as ISO 32000-2 asks, and is also tried the way pdf.js prepares it and as typed. pdf.js gets the form that opened the file.
32
+
33
+ `deadline` is a `Date.now()` value. There is no default. The run checks it between steps, per image, per box it lays out or paints, per field it applies, and inside the PDF reader and the XML parser. Once it has passed, the run returns `failed` with a `deadline` note. pdf.js's own parsing and layout cannot be interrupted, so a run can overshoot the deadline by however long one pdf.js call takes. For a hard bound on time and memory, run `flattenXfa` in a worker thread with `resourceLimits` and terminate the worker when it is late.
34
+
35
+ ### Notes
36
+
37
+ Each note names what was not drawn or done. Kinds so far:
38
+
39
+ - `unencodable-text`: characters the standard 14 fonts cannot show under WinAnsiEncoding. They are drawn as `?`, or without their accent where one can be dropped. The note lists their code points.
40
+ - `image-format`: an image in a format the decoder does not take, for example a TIFF with JPEG or fax compression.
41
+ - `image-source`: an image whose data pdf.js did not hand over.
42
+ - `image-href`: an image the template names only by a path to a file that the PDF does not carry. The note gives the path.
43
+ - `script-not-run`: a script that runs when the form opens or lays out (initialize, docReady, layoutReady, ready, form:ready) or a calculate script. The location is the SOM path of its container, such as `form1[0].page1[0].total[0]`. After 25 notes of one kind, a single note gives the count of the rest.
44
+ - `barcode-type`: a barcode type with no encoder here. The box shows its type name.
45
+ - `barcode-data`: a barcode value the symbology cannot hold.
46
+ - `barcode-empty`: a barcode with no value. Scripts usually compute these.
47
+ - `template-unread`: the XFA packets could not be read, so the form is drawn as pdf.js gives it, without pictures, check marks, edge styles or barcodes.
48
+ - `pattern-approximated`: a repeating gradient drawn as its average color.
49
+ - `svg-path`: a shape path with commands the renderer does not draw.
50
+ - `layout-repair`: pdf.js could not lay the form out as written, and laid out a repaired copy instead. The note says what the copy changed.
51
+ - `field-error`: applying the template to one field threw. That field keeps what pdf.js drew; the rest of the form is still drawn.
52
+ - `layout-error`, `render-error`, `deadline`, `too-large`, `too-complex`: why a run failed.
53
+
54
+ ### Command line
55
+
56
+ ```sh
57
+ xfa-flatten [--password <pw>]... in.pdf out.pdf
58
+ ```
59
+
60
+ It prints the status and the notes, and writes `out.pdf` only when the status is `flattened`. The exit code is 1 when the run fails and 2 for wrong arguments.
61
+
62
+ ## How it works
63
+
64
+ pdf.js opens the file with `enableXfa: true`, binds the data to the template and lays the form out into pages. `doc.allXfaHtml` returns the result as a tree of HTML-like nodes with CSS classes and inline styles. pdf.js never runs the form's scripts, and version 6 has no eval code path at all.
65
+
66
+ xfa-flatten walks that tree. pdf.js gives most boxes an explicit size and position in CSS px, and one px there is one PDF point. Where pdf.js leaves placement to CSS, xfa-flatten works it out: flex rows and columns, block flow, text wrapping, percentages, and captions sized to their text. It measures text with the Adobe Core14 AFM widths and narrows Helvetica for Myriad Pro and Calibri text, so lines break about where pdf.js expected.
67
+
68
+ pdf.js leaves things out of that tree: picture clauses, check button shapes and marks, edge strokes, corners, barcodes and scripts. So xfa-flatten also reads the XFA packets from the PDF itself, with a small reader for the cross-reference table, object streams, the usual filters and the standard security handler (RC4, AES-128 and AES-256). It matches each pdf.js node to its template element by kind, name and the order of pdf.js's ids, inside the already matched parent. From the template it then:
69
+
70
+ - formats field values with their display picture (`format/picture`, else the ui's picture): dates, times, date-times, numbers, currency and text masks, with month and day names, number symbols and currency from the form's `localeSet` packet, and en_US when the packet has no matching locale. A date stored in a bind picture is read back to canonical form first. A value the picture cannot format shows as stored, as Adobe Reader does.
71
+ - shows a choice list value that is not one of its items as the value itself, where pdf.js shows a blank.
72
+ - draws check buttons as square or round with their mark (check, circle, cross, diamond, square or star) for the on state, a gray mark for the neutral state and none for off.
73
+ - draws edges as solid, dashed, dotted, dashDot, dashDotDot, or with the 3D styles lowered, raised, etched and embossed, and corners as round, inverted or notched. pdf.js already places a container's border box for its hand. For a ui's own border, xfa-flatten applies the hand itself.
74
+ - draws Code 39, Code 128, QR Code and PDF417 barcodes from the field's data value.
75
+ - decodes TIFF images: uncompressed, PackBits, LZW and Deflate, in strips or tiles, 1 to 16 bits, gray, RGB, palette and CMYK, with alpha.
76
+
77
+ A small writer then builds a new single-revision PDF. Text uses the standard 14 fonts with WinAnsiEncoding, so no font is embedded. JPEG images pass through as DCTDecode. PNG, GIF, BMP and TIFF images are decoded and written with FlateDecode, and their transparency becomes a soft mask.
78
+
79
+ pdf.js stops before laying out some forms that a reader shows. When it fails, xfa-flatten gives it a copy of the PDF with an incremental update and tries once more. The copy is only for pdf.js; the output is still written from scratch, and the caller's bytes are not changed. The update adds an empty `/DR /Font` dictionary when the AcroForm lists no fonts, so that pdf.js loads its own substitutes. It drops the `ref` of every `<traverse>`, the tab order, when pdf.js cannot follow one. And when every page area of a page set has a finite `occur` maximum and the content needs more pages, it lifts the maximum of the last page area, so the extra pages repeat it. Without that, pdf.js recurses until the stack runs out. A form pdf.js lays out the first time gets none of this.
80
+
81
+ pdf.js measures some rich text short, lists and paragraphs that hold only a line break in particular. Where such a draw has no fixed height in the template, and neither have the boxes around it, xfa-flatten makes it taller and moves the content after it in the same flow down. It never moves anything past the bottom of the content area or into a box below. Text that still does not fit is drawn with tighter line spacing, down to three quarters of the normal pitch.
82
+
83
+ pdf.js reads its standard font files from the `standard_fonts` directory of the installed pdfjs-dist when a form does not embed its fonts. A bundled deployment has to ship that directory.
84
+
85
+ ## Limits
86
+
87
+ These are known and planned:
88
+
89
+ - Scripts never run. A form whose scripts fill in values, hide or repeat parts, or number its pages shows the state before any script ran. The notes list each such script.
90
+ - Text pdf.js measured short grows only into space the page has left. Where the content area is full, or the draw sits in a positioned subform, it gets tighter line spacing instead and can still overlap what follows.
91
+ - Pagination is pdf.js's. It ignores `pageEven` and `pageOdd` breaks, and drops a break whose target names a page or content area by SOM path instead of by id. It also drops a `pageArea` break with no target and `startNew="0"`. It does not always repeat an overflow leader, such as a table's header row, at the top of the next page.
92
+ - A form whose template is outside the XFA template namespace has nothing to lay out. The run fails with a note that says so.
93
+ - The 3D edge shades are a gray pair (or a darker and lighter shade of a colored edge) chosen here, not taken from Adobe Reader.
94
+ - A picture's `%` prints the percent sign and does not scale the value. Forms in the wild store 8.75 for 8.75%.
95
+ - PDF417 uses byte compaction only, so symbols are larger than text compaction would make them.
96
+ - QR Code and PDF417 carry text in ISO 8859-1 when every character fits it, and otherwise in UTF-8 behind the ECI designator for UTF-8. A scanner without ECI support reads the UTF-8 bytes as Latin-1.
97
+ - Code 39 draws the modulo 43 check character when the template's `checksum` is anything but `none`. Code 128 always carries its own check character.
98
+
99
+ Hostile files hit these size limits, each refused before anything that size is allocated:
100
+
101
+ - The XFA packets may decode to 16 MiB in all, and the streams the reader decodes to 64 MiB in all. A form past either is not handed to pdf.js and fails with a `too-large` note. The largest form in the test corpus decodes to 2.4 MB.
102
+ - The PDF reader may walk 16 times the file's length plus 8 MiB. A damaged file that needs more fails with a `too-complex` note before pdf.js sees it.
103
+ - Images may have 50 million pixels. A PNG, TIFF strip or tile that decodes past its declared size is not drawn, and gets an `image-format` note. TIFF images take at most 8 samples per pixel.
104
+ - XML elements nest at most 1000 deep.
105
+ - Code 39 and Code 128 take 1000 characters, QR Code 2953 bytes and PDF417 1850 bytes. A longer value gets a `barcode-data` note.
106
+
107
+ ## License
108
+
109
+ MIT. `src/font-metrics.ts` holds glyph widths generated by `scripts/make-font-metrics.js` from Adobe's Core14 AFM files, whose license allows copying and distributing them.
110
+
111
+ ## Third-party code
112
+
113
+ `src/pdf417-table.ts` holds the PDF417 symbol character patterns of ISO/IEC 15438, copied from ZXing's PDF417 encoder (`core/src/main/java/com/google/zxing/pdf417/encoder/PDF417.java`, https://github.com/zxing/zxing). ZXing is licensed under the Apache License, Version 2.0. The package ships the license text as `LICENSE-APACHE-2.0` and the attribution in `NOTICE`. The rest of the package is MIT.
@@ -0,0 +1,11 @@
1
+ import { type Encoded } from './barcode';
2
+ import type { Canvas } from './canvas';
3
+ import type { Rgb } from './css';
4
+ import type { BarcodeSpec } from './xfa-spec';
5
+ export interface BarcodeEnv {
6
+ note(kind: string, detail: string): void;
7
+ }
8
+ /** Encodes by XFA barcode type name; undefined for a type with no encoder, null when the data does not fit it. */
9
+ export declare function encodeBarcode(spec: BarcodeSpec, columnsHint: number): Encoded | null | undefined;
10
+ /** Paints a barcode in the content box x, y, w, h. */
11
+ export declare function paintBarcode(canvas: Canvas, spec: BarcodeSpec, x: number, y: number, w: number, h: number, color: Rgb, env: BarcodeEnv): void;
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ // Draws a field's barcode into its box, scaled down when the template's module size does not fit.
3
+ // Types without an encoder, and data an encoder cannot take, get a labelled empty box and a note.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.encodeBarcode = encodeBarcode;
6
+ exports.paintBarcode = paintBarcode;
7
+ const barcode_1 = require("./barcode");
8
+ const fonts_1 = require("./fonts");
9
+ function f(n) {
10
+ if (!Number.isFinite(n))
11
+ return '0';
12
+ const s = n.toFixed(3).replace(/0+$/, '').replace(/\.$/, '');
13
+ return s === '-0' ? '0' : s;
14
+ }
15
+ /** Encodes by XFA barcode type name; undefined for a type with no encoder, null when the data does not fit it. */
16
+ function encodeBarcode(spec, columnsHint) {
17
+ const t = spec.type.toLowerCase();
18
+ if (t === 'code3of9' || t === 'code39' || t === 'code3of9extended') {
19
+ // Code 39's only check character is modulo 43; any checksum other than none asks for it.
20
+ const checkDigit = spec.checksum !== '' && spec.checksum !== 'none';
21
+ return (0, barcode_1.encodeCode39)(spec.data, spec.wideNarrowRatio, { extended: t === 'code3of9extended', checkDigit, printCheckDigit: checkDigit && spec.printCheckDigit });
22
+ }
23
+ if (t === 'code128' || t === 'code128a' || t === 'code128b' || t === 'code128c')
24
+ return (0, barcode_1.encodeCode128)(spec.data);
25
+ if (t === 'qrcode')
26
+ return (0, barcode_1.encodeQr)(spec.data, spec.errorCorrectionLevel);
27
+ if (t === 'pdf417') {
28
+ const mw = spec.moduleWidth ?? 0;
29
+ const mh = spec.moduleHeight ?? 0;
30
+ // Rows are listed once and drawn rowH modules tall, so a large ratio costs nothing; the painter scales to the box.
31
+ const rowH = mw > 0 && mh > 0 ? Math.max(1, Math.round(mh / mw)) : 3;
32
+ return (0, barcode_1.encodePdf417)(spec.data, spec.errorCorrectionLevel, spec.dataColumnCount || columnsHint, rowH);
33
+ }
34
+ return undefined;
35
+ }
36
+ function label(canvas, text, x, y, w, h, color) {
37
+ canvas.strokePath(`${f(x + 0.25)} ${f(y + 0.25)} ${f(w - 0.5)} ${f(h - 0.5)} re`, [x, y, x + w, y + h], color, 0.5, null);
38
+ const size = Math.max(4, Math.min(8, h * 0.4));
39
+ const { bytes } = (0, fonts_1.encodeWinAnsi)(text);
40
+ const width = (bytes.reduce((s, b) => s + ((0, fonts_1.metricsOf)('Helvetica').widths[b] ?? 0), 0) * size) / 1000;
41
+ canvas.save();
42
+ canvas.clipRect(x, y, w, h);
43
+ canvas.text('Helvetica', size, x + Math.max(1, (w - width) / 2), y + h / 2 + size * 0.35, bytes, color, { width });
44
+ canvas.restore();
45
+ }
46
+ /** Paints a barcode in the content box x, y, w, h. */
47
+ function paintBarcode(canvas, spec, x, y, w, h, color, env) {
48
+ if (w <= 0 || h <= 0)
49
+ return;
50
+ if (spec.data === '') {
51
+ env.note('barcode-empty', `A barcode of type ${spec.type} had no value to draw; a script usually computes it.`);
52
+ return;
53
+ }
54
+ // PDF417 columns: as many as fit the box width at the template's module width.
55
+ let hint = 0;
56
+ if (spec.type.toLowerCase() === 'pdf417' && spec.moduleWidth)
57
+ hint = Math.max(1, Math.min(30, Math.floor((w / spec.moduleWidth - 73) / 17)));
58
+ const enc = encodeBarcode(spec, hint);
59
+ if (enc === undefined) {
60
+ env.note('barcode-type', `A barcode of type ${spec.type} was not drawn; this type has no encoder here.`);
61
+ label(canvas, `barcode: ${spec.type}`, x, y, w, h, color);
62
+ return;
63
+ }
64
+ if (enc === null) {
65
+ env.note('barcode-data', `A barcode of type ${spec.type} was not drawn; its value does not fit the symbology.`);
66
+ label(canvas, `barcode: ${spec.type}`, x, y, w, h, color);
67
+ return;
68
+ }
69
+ if (enc.kind === 'linear') {
70
+ const quiet = 10;
71
+ const modules = enc.widths.reduce((s, v) => s + v, 0) + 2 * quiet;
72
+ const mw = Math.min(spec.moduleWidth ?? Number.POSITIVE_INFINITY, w / modules);
73
+ const showText = spec.textLocation !== 'none';
74
+ const textSize = showText ? Math.max(4, Math.min(9, h * 0.18)) : 0;
75
+ const barH = h - (showText ? textSize * 1.3 : 0);
76
+ const total = modules * mw;
77
+ let cx = x + (w - total) / 2 + quiet * mw;
78
+ const top = spec.textLocation.startsWith('above') ? y + textSize * 1.3 : y;
79
+ enc.widths.forEach((n, i) => {
80
+ if (i % 2 === 0)
81
+ canvas.fillRect(cx, top, n * mw, barH, color);
82
+ cx += n * mw;
83
+ });
84
+ if (showText) {
85
+ const { bytes } = (0, fonts_1.encodeWinAnsi)(enc.text);
86
+ const tw = (bytes.reduce((s, b) => s + ((0, fonts_1.metricsOf)('Helvetica').widths[b] ?? 0), 0) * textSize) / 1000;
87
+ const ty = spec.textLocation.startsWith('above') ? y + textSize : y + barH + textSize * 1.1;
88
+ canvas.text('Helvetica', textSize, x + (w - tw) / 2, ty, bytes, color, { width: tw });
89
+ }
90
+ return;
91
+ }
92
+ // Each logical row is drawn rowHeight modules tall. In module heights, the symbol is rows * rowHeight tall plus
93
+ // the quiet zone; mh is one module's height.
94
+ const rows = enc.rows.length;
95
+ const tall = rows * enc.rowHeight;
96
+ const cols = enc.rows[0]?.length ?? 0;
97
+ const q = enc.quiet;
98
+ let mw = spec.moduleWidth ?? Number.POSITIVE_INFINITY;
99
+ let mh = enc.rowHeight > 1 ? mw : (spec.moduleHeight ?? mw);
100
+ if (spec.type.toLowerCase() === 'qrcode')
101
+ mh = mw;
102
+ const fitW = w / (cols + 2 * q);
103
+ const fitH = h / (tall + 2 * q);
104
+ const scale = Math.min(1, fitW / mw, fitH / mh);
105
+ if (!Number.isFinite(mw)) {
106
+ mw = Math.min(fitW, fitH);
107
+ mh = mw;
108
+ }
109
+ else {
110
+ mw *= scale;
111
+ mh *= scale;
112
+ }
113
+ const rowPt = mh * enc.rowHeight;
114
+ const ox = x + (w - cols * mw) / 2;
115
+ const oy = y + (h - rows * rowPt) / 2;
116
+ // One rectangle per run of dark modules in a row keeps the content stream small.
117
+ const ops = [];
118
+ for (let r = 0; r < rows; r++) {
119
+ const row = enc.rows[r];
120
+ let c = 0;
121
+ while (c < cols) {
122
+ if (!row[c]) {
123
+ c++;
124
+ continue;
125
+ }
126
+ let e = c;
127
+ while (e < cols && row[e])
128
+ e++;
129
+ ops.push(`${f(ox + c * mw)} ${f(oy + r * rowPt)} ${f((e - c) * mw)} ${f(rowPt)} re`);
130
+ c = e;
131
+ }
132
+ }
133
+ if (ops.length)
134
+ canvas.fillPath(ops.join(' '), [ox, oy, ox + cols * mw, oy + rows * rowPt], color);
135
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * A linear code's module widths, or a 2D code's grid. A matrix lists each logical row once; rowHeight is how many
3
+ * modules tall each row is drawn (PDF417 rows are taller than wide, QR modules are square).
4
+ */
5
+ export type Encoded = {
6
+ kind: 'linear';
7
+ widths: number[];
8
+ text: string;
9
+ } | {
10
+ kind: 'matrix';
11
+ rows: boolean[][];
12
+ rowHeight: number;
13
+ quiet: number;
14
+ };
15
+ /** The longest value a linear code (Code 39, Code 128) takes. A longer one could not be printed at a readable size. */
16
+ export declare const MAX_LINEAR_LENGTH = 1000;
17
+ export interface Code39Options {
18
+ /** Full ASCII: encode every ASCII character with the shift pairs, instead of upper-casing. */
19
+ extended?: boolean;
20
+ /** Append the modulo 43 check character. */
21
+ checkDigit?: boolean;
22
+ /** Show the check character in the human-readable text. */
23
+ printCheckDigit?: boolean;
24
+ }
25
+ /**
26
+ * Code 39. Plain Code 39 upper-cases the value and takes 0-9, A-Z and - . space $ / + %. The extended form takes any
27
+ * ASCII character. Null for a value the symbology cannot carry or longer than MAX_LINEAR_LENGTH.
28
+ */
29
+ export declare function encodeCode39(data: string, ratio?: number, options?: Code39Options): Encoded | null;
30
+ /**
31
+ * Code 128 with code sets B and C (and A for control characters), switching to C for runs of four or more digits.
32
+ * Null for a character outside ASCII or a value longer than MAX_LINEAR_LENGTH.
33
+ */
34
+ export declare function encodeCode128(data: string): Encoded | null;
35
+ /**
36
+ * QR Code in byte mode. eclIndex 0 to 3 is L, M, Q, H. Text outside ISO 8859-1 goes as UTF-8 behind an ECI 26
37
+ * designator.
38
+ */
39
+ export declare function encodeQr(data: string, eclIndex: number): Encoded | null;
40
+ /**
41
+ * PDF417 in byte compaction. columns is the preferred number of data columns (1 to 30); 0 asks for a near-square
42
+ * symbol. When the data does not fit at that width, the nearest column count it fits is taken. rowHeight is the row
43
+ * height in modules; each row is listed once. Text outside ISO 8859-1 goes as UTF-8 behind an ECI 26 designator.
44
+ */
45
+ export declare function encodePdf417(data: string, level: number, columns: number, rowHeight: number): Encoded | null;