@wirabyte/w-pdfmaker 0.0.0-stage → 1.0.2
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/CHANGELOG.md +53 -0
- package/LICENSE +22 -0
- package/NOTICE.md +39 -0
- package/README.md +106 -2
- package/build/fonts/Roboto/Roboto-Italic.ttf +0 -0
- package/build/fonts/Roboto/Roboto-Medium.ttf +0 -0
- package/build/fonts/Roboto/Roboto-MediumItalic.ttf +0 -0
- package/build/fonts/Roboto/Roboto-Regular.ttf +0 -0
- package/build/fonts/Roboto.js +27 -0
- package/build/pdfmake.js +103161 -0
- package/build/pdfmake.js.map +1 -0
- package/build/pdfmake.min.js +3 -0
- package/build/pdfmake.min.js.map +1 -0
- package/build/standard-fonts/Courier.js +9 -0
- package/build/standard-fonts/Helvetica.js +9 -0
- package/build/standard-fonts/Symbol.js +9 -0
- package/build/standard-fonts/Times.js +9 -0
- package/build/standard-fonts/ZapfDingbats.js +9 -0
- package/build/vfs_fonts.js +6 -0
- package/build-vfs.js +44 -0
- package/fonts/Roboto/Roboto-Italic.ttf +0 -0
- package/fonts/Roboto/Roboto-Medium.ttf +0 -0
- package/fonts/Roboto/Roboto-MediumItalic.ttf +0 -0
- package/fonts/Roboto/Roboto-Regular.ttf +0 -0
- package/fonts/Roboto.js +8 -0
- package/fonts/THSarabunIT9/LICENSE.txt +7 -0
- package/fonts/THSarabunIT9/THSarabunIT9-Bold.ttf +0 -0
- package/fonts/THSarabunIT9/THSarabunIT9-BoldItalic.ttf +0 -0
- package/fonts/THSarabunIT9/THSarabunIT9-Italic.ttf +0 -0
- package/fonts/THSarabunIT9/THSarabunIT9.ttf +0 -0
- package/fonts/THSarabunNew/COPYING.GPLv2 +339 -0
- package/fonts/THSarabunNew/LICENSE.txt +13 -0
- package/fonts/THSarabunNew/THSarabunNew-Bold.ttf +0 -0
- package/fonts/THSarabunNew/THSarabunNew-BoldItalic.ttf +0 -0
- package/fonts/THSarabunNew/THSarabunNew-Italic.ttf +0 -0
- package/fonts/THSarabunNew/THSarabunNew.ttf +0 -0
- package/index.d.ts +167 -0
- package/interfaces.d.ts +2779 -0
- package/js/DocMeasure.js +695 -0
- package/js/DocPreprocessor.js +263 -0
- package/js/DocumentContext.js +563 -0
- package/js/ElementWriter.js +488 -0
- package/js/LayoutBuilder.js +1525 -0
- package/js/Line.js +105 -0
- package/js/OutputDocument.js +73 -0
- package/js/OutputDocumentServer.js +34 -0
- package/js/PDFDocument.js +322 -0
- package/js/PageElementWriter.js +302 -0
- package/js/PageSize.js +74 -0
- package/js/Printer.js +275 -0
- package/js/Renderer.js +439 -0
- package/js/SVGMeasure.js +94 -0
- package/js/StyleContextStack.js +191 -0
- package/js/TableProcessor.js +658 -0
- package/js/TextBreaker.js +164 -0
- package/js/TextDecorator.js +164 -0
- package/js/TextInlines.js +212 -0
- package/js/URLResolver.js +122 -0
- package/js/base.js +125 -0
- package/js/browser-extensions/OutputDocumentBrowser.js +82 -0
- package/js/browser-extensions/fonts/Roboto.js +38 -0
- package/js/browser-extensions/fonts/thai.js +28 -0
- package/js/browser-extensions/index.js +88 -0
- package/js/browser-extensions/pageUrls.js +79 -0
- package/js/browser-extensions/pdfMake.js +3 -0
- package/js/browser-extensions/standard-fonts/Courier.js +20 -0
- package/js/browser-extensions/standard-fonts/Helvetica.js +20 -0
- package/js/browser-extensions/standard-fonts/Symbol.js +17 -0
- package/js/browser-extensions/standard-fonts/Times.js +20 -0
- package/js/browser-extensions/standard-fonts/ZapfDingbats.js +17 -0
- package/js/browser-extensions/virtual-fs-cjs.js +3 -0
- package/js/columnCalculator.js +159 -0
- package/js/helpers/node.js +122 -0
- package/js/helpers/tools.js +46 -0
- package/js/helpers/variableType.js +59 -0
- package/js/imageFallback.js +23 -0
- package/js/index.js +45 -0
- package/js/mergeStamp.js +194 -0
- package/js/pageNumbering.js +48 -0
- package/js/qrEnc.js +721 -0
- package/js/standardPageSizes.js +56 -0
- package/js/tableLayouts.js +98 -0
- package/js/thai.js +201 -0
- package/js/virtual-fs.js +82 -0
- package/package.json +93 -4
- package/skills/w-pdfmaker/SKILL.md +171 -0
- package/skills/w-pdfmaker/references/browser.md +36 -0
- package/skills/w-pdfmaker/references/document-definition.md +241 -0
- package/skills/w-pdfmaker/references/images.md +90 -0
- package/skills/w-pdfmaker/references/merge-stamp.md +94 -0
- package/skills/w-pdfmaker/references/thai.md +67 -0
- package/src/DocMeasure.js +780 -0
- package/src/DocPreprocessor.js +293 -0
- package/src/DocumentContext.js +605 -0
- package/src/ElementWriter.js +550 -0
- package/src/LayoutBuilder.js +1689 -0
- package/src/Line.js +114 -0
- package/src/OutputDocument.js +75 -0
- package/src/OutputDocumentServer.js +38 -0
- package/src/PDFDocument.js +352 -0
- package/src/PageElementWriter.js +343 -0
- package/src/PageSize.js +53 -0
- package/src/Printer.js +289 -0
- package/src/Renderer.js +468 -0
- package/src/SVGMeasure.js +109 -0
- package/src/StyleContextStack.js +208 -0
- package/src/TableProcessor.js +719 -0
- package/src/TextBreaker.js +166 -0
- package/src/TextDecorator.js +191 -0
- package/src/TextInlines.js +229 -0
- package/src/URLResolver.js +122 -0
- package/src/base.js +143 -0
- package/src/browser-extensions/OutputDocumentBrowser.js +80 -0
- package/src/browser-extensions/fonts/Roboto.js +27 -0
- package/src/browser-extensions/fonts/thai.js +23 -0
- package/src/browser-extensions/index.js +91 -0
- package/src/browser-extensions/pageUrls.js +67 -0
- package/src/browser-extensions/pdfMake.js +1 -0
- package/src/browser-extensions/standard-fonts/Courier.js +25 -0
- package/src/browser-extensions/standard-fonts/Helvetica.js +25 -0
- package/src/browser-extensions/standard-fonts/Symbol.js +17 -0
- package/src/browser-extensions/standard-fonts/Times.js +25 -0
- package/src/browser-extensions/standard-fonts/ZapfDingbats.js +17 -0
- package/src/browser-extensions/virtual-fs-cjs.js +1 -0
- package/src/columnCalculator.js +160 -0
- package/src/helpers/node.js +134 -0
- package/src/helpers/tools.js +44 -0
- package/src/helpers/variableType.js +50 -0
- package/src/imageFallback.js +18 -0
- package/src/index.js +45 -0
- package/src/mergeStamp.js +132 -0
- package/src/pageNumbering.js +45 -0
- package/src/qrEnc.js +796 -0
- package/src/standardPageSizes.js +52 -0
- package/src/tableLayouts.js +100 -0
- package/src/thai.js +170 -0
- package/src/virtual-fs.js +92 -0
- package/standard-fonts/Courier.js +8 -0
- package/standard-fonts/Helvetica.js +8 -0
- package/standard-fonts/Symbol.js +5 -0
- package/standard-fonts/Times.js +8 -0
- package/standard-fonts/ZapfDingbats.js +5 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: w-pdfmaker
|
|
3
|
+
description: >
|
|
4
|
+
How to generate and edit PDFs with @wirabyte/w-pdfmaker, the company's fork of pdfmake 0.3 with Thai built in
|
|
5
|
+
(TH Sarabun fonts, Thai line breaking, distributed alignment, correct ำ copy/search) plus merging and stamping
|
|
6
|
+
existing PDFs. Use this whenever code imports or should import @wirabyte/w-pdfmaker, or the user wants to build,
|
|
7
|
+
change or debug a PDF (report, thesis, memo, บันทึกข้อความ, certificate, form, letter, receipt) in a project that
|
|
8
|
+
depends on it: Thai text layout, tables, table of contents (สารบัญ), page numbers (ก ข ค / 1 2 3 per section),
|
|
9
|
+
watermarks, signature images, joining PDFs, attachments, or migrating from pdfmake / pdf-lib. Use it even when the user only says "pdfmake" or "make a PDF" in such a project.
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
# w-pdfmaker
|
|
13
|
+
|
|
14
|
+
`@wirabyte/w-pdfmaker` is pdfmake 0.3.15 with Thai support built in and two extra functions (`merge`, `stamp`).
|
|
15
|
+
Document definitions are plain pdfmake 0.3, so pdfmake knowledge applies; this skill covers what is different and
|
|
16
|
+
the mistakes that are easy to make. The library already does a lot that older pdfmake projects hand-rolled, so
|
|
17
|
+
before writing font setup, word-cutting, `vfs_fonts`, or pdf-lib code, check here whether it is built in.
|
|
18
|
+
|
|
19
|
+
## Setup
|
|
20
|
+
|
|
21
|
+
`npm install @wirabyte/w-pdfmaker` (public on npmjs.com, no token needed). Version 1.0.0 was only on GitHub
|
|
22
|
+
Packages: if the project's `.npmrc` still has `@wirabyte:registry=https://npm.pkg.github.com`, remove that line.
|
|
23
|
+
Node.js >= 20.19. TypeScript types are included. When migrating, remove `pdfmake`, `@types/pdfmake`, `pdf-lib`, `@pdf-lib/fontkit` and any Thai font
|
|
24
|
+
files or line-breaking patches the project carried.
|
|
25
|
+
|
|
26
|
+
Import it as one object:
|
|
27
|
+
|
|
28
|
+
```js
|
|
29
|
+
const pdfmake = require('@wirabyte/w-pdfmaker'); // CommonJS
|
|
30
|
+
import pdfmake from '@wirabyte/w-pdfmaker'; // ESM / TS (esModuleInterop)
|
|
31
|
+
import type { Content, TDocumentDefinitions } from '@wirabyte/w-pdfmaker/interfaces';
|
|
32
|
+
// NodeNext ESM resolution needs '@wirabyte/w-pdfmaker/interfaces.js'
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`import { createPdf }` and `import * as pdfmake` type-check but fail at runtime: the module is a single object whose
|
|
36
|
+
functions are methods (they use `this`).
|
|
37
|
+
|
|
38
|
+
## Basic use
|
|
39
|
+
|
|
40
|
+
```js
|
|
41
|
+
const doc = {
|
|
42
|
+
pageSize: 'A4',
|
|
43
|
+
pageMargins: [85, 70, 57, 57], // [left, top, right, bottom] in pt (1 cm ≈ 28.35 pt)
|
|
44
|
+
content: [
|
|
45
|
+
{ text: 'บันทึกข้อความ', fontSize: 29, bold: true, alignment: 'center' },
|
|
46
|
+
{ text: thaiParagraph, alignment: 'distribute', margin: [0, 8, 0, 0] },
|
|
47
|
+
],
|
|
48
|
+
footer: (currentPage, pageCount) => ({ text: `${currentPage}/${pageCount}`, alignment: 'center' }),
|
|
49
|
+
};
|
|
50
|
+
const pdf = await pdfmake.createPdf(doc).getBuffer(); // Buffer
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Output: `getBuffer()`, `getBase64()`, `getDataUrl()`, `getStream()`; Node also `write(path)`; browser also
|
|
54
|
+
`download(name)`, `open()`, `print()`, `getBlob()`. Options: `createPdf(doc, { unbreakableOverflow: 'error' })` makes
|
|
55
|
+
`unbreakable` content that cannot fit a page reject instead of being split.
|
|
56
|
+
|
|
57
|
+
For the full document-definition syntax (tables, columns, lists, header/footer, sections, TOC, watermark, security)
|
|
58
|
+
read `references/document-definition.md`.
|
|
59
|
+
|
|
60
|
+
## Thai: what is automatic
|
|
61
|
+
|
|
62
|
+
- **Fonts are registered.** With no font set, text uses `THSarabunNew` at **16pt**. `THSarabunIT9` (TH SarabunIT๙)
|
|
63
|
+
is also registered: it draws digits as Thai numerals while the text stays `0–9`, so copy and search see Arabic
|
|
64
|
+
digits. Official documents usually set `defaultStyle: { font: 'THSarabunIT9' }`.
|
|
65
|
+
- **Line breaking** happens between Thai words automatically. Do not insert zero-width spaces or run wordcut.
|
|
66
|
+
- **Justified Thai: use `alignment: 'distribute'`**, which spreads the space between characters like Word's
|
|
67
|
+
"Thai Distributed". `'justify'` spreads it between words, and since every Thai word boundary is a break point,
|
|
68
|
+
Thai lines get visible gaps; keep `'justify'` for English.
|
|
69
|
+
- **ำ (SARA AM)** copies and searches correctly in the output; nothing to do.
|
|
70
|
+
|
|
71
|
+
To add fonts, use `pdfmake.addFonts({...})`, not `setFonts`: `setFonts` replaces everything, and without
|
|
72
|
+
`THSarabunNew` the defaults fall back to pdfmake's Roboto 12pt. Roboto is not registered in Node; add it with
|
|
73
|
+
`pdfmake.addFonts(require('@wirabyte/w-pdfmaker/fonts/Roboto'))`. Details: `references/thai.md`.
|
|
74
|
+
|
|
75
|
+
## Images
|
|
76
|
+
|
|
77
|
+
```js
|
|
78
|
+
{ image: path.join(__dirname, '../assets/logo.png'), width: 60 } // JPEG / PNG by file path (Node)
|
|
79
|
+
{ svg: path.join(__dirname, '../assets/garuda.svg'), width: 80 } // SVG file (or SVG markup string)
|
|
80
|
+
{ image: 'logo', width: 60 } // name from the images dictionary
|
|
81
|
+
{ image: user.signaturePath ?? '', fallback: true, width: 100, height: 40 } // blank space if missing
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
- Relative paths resolve against `process.cwd()`, not the source file, so build them from `__dirname`.
|
|
85
|
+
- `images: { logo: ... }` takes a path, data URL, `Buffer` / `Uint8Array` / `ArrayBuffer`, `https://` URL, or
|
|
86
|
+
`{ url, headers }`. Use it to reuse one image or to load URLs.
|
|
87
|
+
- `fallback: true` leaves empty space when the source is empty, the file does not exist, or a download fails. Give
|
|
88
|
+
both `width` and `height` to reserve the exact space. Access-policy denials and broken files still throw.
|
|
89
|
+
- Node blocks URL downloads by default (SSRF protection) and allows local files. To allow URLs:
|
|
90
|
+
`pdfmake.setUrlAccessPolicy(url => url.startsWith('https://files.example.com/'))`. If you restrict local files
|
|
91
|
+
with `setLocalAccessPolicy`, also allow the package's `fonts` folder, or every document with text fails.
|
|
92
|
+
- In the browser, paths are URLs relative to the page.
|
|
93
|
+
|
|
94
|
+
Details and edge cases: `references/images.md`.
|
|
95
|
+
|
|
96
|
+
## Reports: table of contents and page numbers
|
|
97
|
+
|
|
98
|
+
Thai reports and theses number the front matter ก ข ค and the chapters 1 2 3, like Word's "Page Number Format".
|
|
99
|
+
Use top-level `section`s with `pageNumbering`, and print `pageLabel` (the 4th footer argument):
|
|
100
|
+
|
|
101
|
+
```js
|
|
102
|
+
const makeDoc = () => ({
|
|
103
|
+
footer: (currentPage, pageCount, pageSize, pageLabel) => ({ text: pageLabel, alignment: 'center' }),
|
|
104
|
+
content: [
|
|
105
|
+
{ section: [cover], footer: null }, // no number on the cover
|
|
106
|
+
{ section: [abstract, { toc: { title: { text: 'สารบัญ', style: 'h1' }, outlines: true }, pageBreak: 'before' }],
|
|
107
|
+
pageNumbering: { start: 1, format: 'ก' } }, // ก ข ค
|
|
108
|
+
{ section: [
|
|
109
|
+
{ text: 'บทที่ 1 บทนำ', style: 'h1', tocItem: true },
|
|
110
|
+
{ text: '1.1 ความเป็นมา', style: 'h2', tocItem: true, tocLevel: 2 }, // indented, nested bookmark
|
|
111
|
+
chapter1Body,
|
|
112
|
+
], pageNumbering: { start: 1, format: '1' } }, // 1 2 3; later sections continue
|
|
113
|
+
],
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
- Only nodes with `tocItem` appear in a `toc`. A second list (สารบัญตาราง) is `toc: { id: 'tables' }` plus
|
|
118
|
+
`tocItem: 'tables'` on the captions; `tocItem: [true, 'tables']` puts a node in both.
|
|
119
|
+
- Formats: `'1'`, `'i'`, `'I'`, `'๑'`, `'ก'` or `n => string`. `pageReference` and the table of contents use the
|
|
120
|
+
labels too. `currentPage` / `pageCount` in header and footer stay physical page numbers.
|
|
121
|
+
- The table of contents is computed inside `createPdf`. Pages inserted later with `merge` are not counted, and
|
|
122
|
+
`stamp`'s `pageNumber` is physical, so insert attachments only after the last numbered page (or at the end).
|
|
123
|
+
|
|
124
|
+
All options (`hideEmpty`, `sortBy`, styles of entries and numbers): `references/document-definition.md`
|
|
125
|
+
sections 8–9.
|
|
126
|
+
|
|
127
|
+
## Merging and stamping existing PDFs
|
|
128
|
+
|
|
129
|
+
```js
|
|
130
|
+
const merged = await pdfmake.merge([
|
|
131
|
+
{ pdf: mainPdf, to: 3 }, // pages 1–3 (numbered from 1, inclusive)
|
|
132
|
+
'uploads/attachment.pdf', // whole file; a string is a file path, a Buffer/Uint8Array is PDF data
|
|
133
|
+
{ pdf: mainPdf, from: 4 }, // page 4 to the end; a range past the end selects nothing (no error)
|
|
134
|
+
]);
|
|
135
|
+
const out = await pdfmake.stamp(merged, ({ pageNumber, pageCount, height }) => ({
|
|
136
|
+
// bottom right of every page, portrait or landscape: a full-width box at x: 0, text right-aligned inside it
|
|
137
|
+
absolutePosition: { x: 0, y: height - 40 }, // top-left origin of the page as shown
|
|
138
|
+
stack: [{ text: `หน้า ${pageNumber}/${pageCount}`, alignment: 'right', margin: [0, 0, 40, 0] }],
|
|
139
|
+
fontSize: 14,
|
|
140
|
+
}));
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Both return a `Buffer` and work in Node and the browser; do not add pdf-lib for this. `stamp`'s function may be
|
|
144
|
+
async and returns pdfmake content or `null` to leave a page untouched; the content must fit on one page. PDFs locked
|
|
145
|
+
with only an owner password open fine (the output is unencrypted); ones needing a password to open throw
|
|
146
|
+
`NEEDS PASSWORD`. Recipes (attachments after page N, watermark on every page, rotated pages):
|
|
147
|
+
`references/merge-stamp.md`.
|
|
148
|
+
|
|
149
|
+
## Gotchas
|
|
150
|
+
|
|
151
|
+
- **Build a fresh document definition for every `createPdf` call, and never place the same node object twice.**
|
|
152
|
+
Layout writes into the nodes: a second occurrence of a node in one document silently disappears, and a rendered
|
|
153
|
+
definition keeps decisions such as a `fallback` image already replaced by empty space. Use functions:
|
|
154
|
+
`const makeDoc = data => ({ content: [...] })`, `const logo = () => ({ image: LOGO, width: 60 })`.
|
|
155
|
+
- **`margin` is ignored on a node that has `absolutePosition`** (the label silently touches the edge). Put the
|
|
156
|
+
margin on an inner node, as in the `stamp` example above: `{ absolutePosition, stack: [{ text, margin }] }`.
|
|
157
|
+
- Header, footer and background can be functions: `(currentPage, pageCount, pageSize) => Content` and
|
|
158
|
+
`(currentPage, pageSize) => Content`. Leave enough `pageMargins` for them; a TH Sarabun line is ~1.3× the font size (16pt → ~21pt).
|
|
159
|
+
- `section` nodes (pdfmake 0.3) give parts of a document their own page size, orientation, margins, header and
|
|
160
|
+
footer, and are only allowed at the top level of `content`.
|
|
161
|
+
- Content nodes, styles and options are fully typed: when unsure about a property, grep
|
|
162
|
+
`node_modules/@wirabyte/w-pdfmaker/interfaces.d.ts` (and `index.d.ts` for the functions) instead of guessing.
|
|
163
|
+
|
|
164
|
+
## References
|
|
165
|
+
|
|
166
|
+
- `references/document-definition.md`: pdfmake 0.3 document-definition cheat sheet.
|
|
167
|
+
- `references/thai.md`: fonts, sizes, Thai numerals, alignment, mixing fonts.
|
|
168
|
+
- `references/images.md`: image and SVG sources, paths, `fallback`, access policies, browser paths.
|
|
169
|
+
- `references/merge-stamp.md`: `merge` / `stamp` rules and recipes.
|
|
170
|
+
- `references/browser.md`: browser build, bundlers, output methods, virtual file system.
|
|
171
|
+
- pdfmake's own docs for features not changed here: https://pdfmake.github.io/docs/
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Browser
|
|
2
|
+
|
|
3
|
+
The package's `browser` field points to `build/pdfmake.js`; bundlers that read it for browser targets (Vite and
|
|
4
|
+
webpack do by default) use the browser build from the same import:
|
|
5
|
+
|
|
6
|
+
```js
|
|
7
|
+
import pdfmake from '@wirabyte/w-pdfmaker';
|
|
8
|
+
|
|
9
|
+
await pdfmake.createPdf(doc).download('report.pdf'); // save dialog / download
|
|
10
|
+
await pdfmake.createPdf(doc).open(); // new tab (call from a click handler: popup blockers)
|
|
11
|
+
await pdfmake.createPdf(doc).print();
|
|
12
|
+
const blob = await pdfmake.createPdf(doc).getBlob(); // e.g. upload with FormData, or URL.createObjectURL(blob)
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Without a bundler, load `node_modules/@wirabyte/w-pdfmaker/build/pdfmake.min.js` (about 3 MB, includes the Thai
|
|
16
|
+
fonts and pdf-lib) with a `<script>` tag; it defines the global `pdfMake`.
|
|
17
|
+
|
|
18
|
+
What is the same as Node: Thai fonts registered and 16pt default, Thai line breaking, `distribute`, ำ fix, `merge`,
|
|
19
|
+
`stamp`, `fallback`, all document-definition features.
|
|
20
|
+
|
|
21
|
+
What differs:
|
|
22
|
+
|
|
23
|
+
- **Paths are URLs relative to the page** (`image`, `svg`, `images`, and PDFs given to `merge` / `stamp`), downloaded
|
|
24
|
+
before layout. The page must be served over http(s); a `file://` page gets an error explaining this. With a
|
|
25
|
+
bundler, import the asset to get its URL (`import logoUrl from './logo.png'`). Paths used only inside header,
|
|
26
|
+
footer or background functions are not downloaded: put them in `images` and use the name.
|
|
27
|
+
- **URL downloads are allowed by default** (Node blocks them). Restrict with `pdfmake.setUrlAccessPolicy(fn)`.
|
|
28
|
+
- **`write(path)` does not exist**; use `download`, `getBlob`, `getBuffer` or `getBase64`.
|
|
29
|
+
- **Roboto** is registered by name but its font files are not bundled. To use it, load `build/vfs_fonts.js` after
|
|
30
|
+
`pdfmake.min.js` (script tags register it automatically), or with a bundler:
|
|
31
|
+
`import vfs from '@wirabyte/w-pdfmaker/build/vfs_fonts'; pdfmake.addVirtualFileSystem(vfs);`. Thai fonts need
|
|
32
|
+
nothing.
|
|
33
|
+
- **Extra fonts / files**: `pdfmake.addVirtualFileSystem({ 'MyFont.ttf': base64String })` then
|
|
34
|
+
`pdfmake.addFonts({ MyFont: { normal: 'MyFont.ttf' } })`. `pdfmake.addFontContainer({ vfs, fonts })` does both.
|
|
35
|
+
- Generation runs on the main thread; very large documents can freeze the page for a moment. Show a spinner and
|
|
36
|
+
start generation after it renders.
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
# Document definition cheat sheet (pdfmake 0.3)
|
|
2
|
+
|
|
3
|
+
Units are points: 1 cm ≈ 28.35 pt, 1 inch = 72 pt. A4 is 595.28 × 841.89 pt. Every property below is typed in
|
|
4
|
+
`interfaces.d.ts` (`TDocumentDefinitions`, `Content*`, `Style`, `Table`); grep it for anything not listed.
|
|
5
|
+
|
|
6
|
+
## Contents
|
|
7
|
+
|
|
8
|
+
1. Top level
|
|
9
|
+
2. Content nodes and common properties
|
|
10
|
+
3. Text and styles
|
|
11
|
+
4. Columns, stacks, lists
|
|
12
|
+
5. Tables
|
|
13
|
+
6. Positioning and page breaks
|
|
14
|
+
7. Header, footer, background, watermark
|
|
15
|
+
8. Sections
|
|
16
|
+
9. Table of contents, links, references
|
|
17
|
+
10. Canvas and QR codes
|
|
18
|
+
11. Metadata and security
|
|
19
|
+
|
|
20
|
+
## 1. Top level
|
|
21
|
+
|
|
22
|
+
```js
|
|
23
|
+
const doc = {
|
|
24
|
+
content: [...], // required
|
|
25
|
+
pageSize: 'A4', // 'A4' (default), 'A5', 'LETTER', ... or { width, height }; height: 'auto' = one page as tall as the content
|
|
26
|
+
pageOrientation: 'portrait', // or 'landscape'
|
|
27
|
+
pageMargins: [85, 70, 57, 57], // number | [horizontal, vertical] | [left, top, right, bottom]
|
|
28
|
+
defaultStyle: { font: 'THSarabunIT9', fontSize: 16, lineHeight: 1 },
|
|
29
|
+
styles: { title: { fontSize: 20, bold: true, alignment: 'center' } },
|
|
30
|
+
header, footer, background, watermark, // section 7
|
|
31
|
+
images: { logo: '/abs/path/logo.png' }, // see images.md
|
|
32
|
+
info: { title: 'รายงาน', author: 'ฝ่ายวิชาการ' },
|
|
33
|
+
pageBreakBefore: (currentNode, { getFollowingNodesOnPage, getNodesOnNextPage, getPreviousNodesOnPage }) => false,
|
|
34
|
+
language: 'th-TH',
|
|
35
|
+
compress: true,
|
|
36
|
+
};
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## 2. Content nodes and common properties
|
|
40
|
+
|
|
41
|
+
A node is one of: a string (text), an array (stack), or an object with one of these keys: `text`, `stack`,
|
|
42
|
+
`columns`, `ul`, `ol`, `table`, `image`, `svg`, `canvas`, `qr`, `toc`, `pageReference`, `textReference`,
|
|
43
|
+
`attachment`, `section` (top level only).
|
|
44
|
+
|
|
45
|
+
Properties every node accepts:
|
|
46
|
+
|
|
47
|
+
| Property | Meaning |
|
|
48
|
+
|---|---|
|
|
49
|
+
| `style` | name or array of names from `styles` |
|
|
50
|
+
| `margin` | number, `[h, v]` or `[left, top, right, bottom]`; also `marginTop` etc. |
|
|
51
|
+
| `id` | name for `pageReference` / `textReference` / `linkToDestination` |
|
|
52
|
+
| `pageBreak` | `'before'`, `'after'`, `'beforeOdd'`, `'beforeEven'`, `'afterOdd'`, `'afterEven'` |
|
|
53
|
+
| `pageOrientation` | with `pageBreak`: switch orientation from that page |
|
|
54
|
+
| `unbreakable` | keep the node on one page (moves to the next page if it fits there) |
|
|
55
|
+
| `headlineLevel` | marks headings, for `pageBreakBefore` checks |
|
|
56
|
+
| `absolutePosition` / `relativePosition` | `{ x, y }`, section 6 |
|
|
57
|
+
|
|
58
|
+
Do not put the same object in the content twice: pdfmake stores layout state in the node, and the second
|
|
59
|
+
occurrence disappears. For the same reason, build the whole definition in a function and call it for every
|
|
60
|
+
document instead of rendering one object again. Use functions returning fresh objects.
|
|
61
|
+
|
|
62
|
+
## 3. Text and styles
|
|
63
|
+
|
|
64
|
+
```js
|
|
65
|
+
{ text: 'ข้อความ', style: 'body' }
|
|
66
|
+
{ text: ['ปกติ ', { text: 'ตัวหนา', bold: true }, ' และ ', { text: 'ลิงก์', link: 'https://example.com', color: 'blue' }] }
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Style properties (usable on nodes, in `styles`, in `defaultStyle`): `font`, `fontSize`, `lineHeight` (multiplier),
|
|
70
|
+
`bold`, `italics`, `alignment` (`left`, `center`, `right`, `justify`, `distribute` (w-pdfmaker)), `color`,
|
|
71
|
+
`background`, `decoration` (`underline`, `lineThrough`, `overline`), `decorationStyle` (`dashed`, `dotted`,
|
|
72
|
+
`double`, `wavy`), `decorationColor`, `characterSpacing`, `leadingIndent` (first-line indent), `preserveLeadingSpaces`,
|
|
73
|
+
`sup`, `sub`, `opacity`, `noWrap`, `fillColor` (table cells), `columnGap`.
|
|
74
|
+
|
|
75
|
+
First-line indent for Thai paragraphs: `{ text, leadingIndent: 42.5, alignment: 'distribute' }` (1.5 cm).
|
|
76
|
+
|
|
77
|
+
## 4. Columns, stacks, lists
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
{ columns: [
|
|
81
|
+
{ width: 100, text: 'ซ้าย' },
|
|
82
|
+
{ width: '*', text: 'ยืดเต็มที่เหลือ' },
|
|
83
|
+
{ width: 'auto', text: 'พอดีเนื้อหา' },
|
|
84
|
+
], columnGap: 10 }
|
|
85
|
+
|
|
86
|
+
{ stack: ['บรรทัด 1', 'บรรทัด 2'], margin: [0, 10] }
|
|
87
|
+
|
|
88
|
+
{ ul: ['ข้อ ก', 'ข้อ ข'] } // type: 'square' | 'circle' | 'none'
|
|
89
|
+
{ ol: ['ขั้นที่ 1', 'ขั้นที่ 2'], start: 3, separator: ')' } // type: 'lower-alpha', 'upper-roman', ...
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Columns side by side with a signature block: put each signature in its own `stack` inside `columns`, with
|
|
93
|
+
`alignment: 'center'`.
|
|
94
|
+
|
|
95
|
+
## 5. Tables
|
|
96
|
+
|
|
97
|
+
```js
|
|
98
|
+
{
|
|
99
|
+
table: {
|
|
100
|
+
headerRows: 1, // repeated on every page
|
|
101
|
+
widths: [30, '*', 'auto', 80], // number | '*' | 'auto' | '25%'
|
|
102
|
+
dontBreakRows: true, // keep each row on one page
|
|
103
|
+
keepWithHeaderRows: 1,
|
|
104
|
+
body: [
|
|
105
|
+
[{ text: 'ที่', bold: true }, { text: 'รายการ', bold: true }, 'จำนวน', 'หมายเหตุ'],
|
|
106
|
+
['1', { text: 'ยาวสองช่อง', colSpan: 2 }, {}, ''], // a spanned cell still needs a placeholder {}
|
|
107
|
+
[{ text: 'สองแถว', rowSpan: 2 }, 'ก', '1', ''],
|
|
108
|
+
[{}, 'ข', '2', ''],
|
|
109
|
+
],
|
|
110
|
+
},
|
|
111
|
+
layout: 'lightHorizontalLines', // 'noBorders' | 'headerLineOnly' | 'lightHorizontalLines' | custom object
|
|
112
|
+
tableAlignment: 'center', // left | center | right (when narrower than the page)
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Cell properties: `colSpan`, `rowSpan`, `fillColor`, `border: [left, top, right, bottom]` (booleans),
|
|
117
|
+
`borderColor`, `verticalAlignment: 'top' | 'middle' | 'bottom'`, `margin`.
|
|
118
|
+
|
|
119
|
+
Custom layout (also registrable by name with `pdfmake.addTableLayouts({ name: layout })`):
|
|
120
|
+
|
|
121
|
+
```js
|
|
122
|
+
layout: {
|
|
123
|
+
hLineWidth: (i, node) => (i === 0 || i === node.table.body.length ? 1 : 0.5),
|
|
124
|
+
vLineWidth: () => 0.5,
|
|
125
|
+
hLineColor: () => '#999',
|
|
126
|
+
paddingLeft: () => 4, paddingRight: () => 4, paddingTop: () => 2, paddingBottom: () => 2,
|
|
127
|
+
fillColor: (rowIndex) => (rowIndex % 2 === 0 ? '#f3f3f3' : null),
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## 6. Positioning and page breaks
|
|
132
|
+
|
|
133
|
+
- `absolutePosition: { x, y }` places a node at page coordinates (top-left origin, ignores margins and flow).
|
|
134
|
+
- `relativePosition: { x, y }` shifts it from where it would be, without moving what follows.
|
|
135
|
+
- `pageBreak: 'before'` starts a new page. Avoid an orphan heading at the bottom of a page:
|
|
136
|
+
|
|
137
|
+
```js
|
|
138
|
+
pageBreakBefore: (currentNode, { getFollowingNodesOnPage }) =>
|
|
139
|
+
currentNode.headlineLevel === 1 && getFollowingNodesOnPage().length === 0,
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## 7. Header, footer, background, watermark
|
|
143
|
+
|
|
144
|
+
```js
|
|
145
|
+
header: (currentPage, pageCount, pageSize) => currentPage === 1 ? null : { text: `- ${currentPage} -`, alignment: 'center', margin: [0, 20, 0, 0] },
|
|
146
|
+
footer: (currentPage, pageCount) => ({ text: `หน้า ${currentPage} จาก ${pageCount}`, alignment: 'right', margin: [0, 0, 40, 0] }),
|
|
147
|
+
background: (currentPage, pageSize) => ({ canvas: [{ type: 'rect', x: 20, y: 20, w: pageSize.width - 40, h: pageSize.height - 40, lineWidth: 0.5 }] }),
|
|
148
|
+
watermark: { text: 'สำเนา', color: 'red', opacity: 0.15, bold: true, angle: -45 },
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Header and footer are drawn inside the top and bottom page margins, so the margins must be tall enough for them.
|
|
152
|
+
They can also be static content instead of functions. `currentPage` is the physical page; to print the number set by a
|
|
153
|
+
section's `pageNumbering` (section 8), use the 4th argument: `footer: (currentPage, pageCount, pageSize, pageLabel) => pageLabel`.
|
|
154
|
+
|
|
155
|
+
## 8. Sections
|
|
156
|
+
|
|
157
|
+
Top-level `section` nodes start a new page each and can override page settings for their part:
|
|
158
|
+
|
|
159
|
+
```js
|
|
160
|
+
content: [
|
|
161
|
+
{ section: ['หน้าปก'], pageSize: 'A4', pageOrientation: 'portrait', footer: null },
|
|
162
|
+
{ section: [wideTable], pageOrientation: 'landscape', pageMargins: 30 }, // others inherit
|
|
163
|
+
]
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Page numbering per section, like Word (w-pdfmaker): `pageNumbering: { start, format }` on a section. `start` restarts the
|
|
167
|
+
count, `format` is `'1'`, `'i'`, `'I'`, `'๑'`, `'ก'` (ก ข ค without ฃ ฅ) or `n => string`. A section without it continues
|
|
168
|
+
the count and keeps the format. Pages before the first `pageNumbering` count physically. The table of contents,
|
|
169
|
+
`pageReference` and the footer's `pageLabel` argument all use it:
|
|
170
|
+
|
|
171
|
+
```js
|
|
172
|
+
footer: (currentPage, pageCount, pageSize, pageLabel) => ({ text: pageLabel, alignment: 'center' }),
|
|
173
|
+
content: [
|
|
174
|
+
{ section: ['หน้าปก'], footer: null },
|
|
175
|
+
{ section: [preface, toc], pageNumbering: { start: 1, format: 'ก' } }, // ก ข ค
|
|
176
|
+
{ section: [chapter1], pageNumbering: { start: 1, format: '1' } }, // 1 2 3
|
|
177
|
+
{ section: [chapter2] }, // continues 4 5 6
|
|
178
|
+
]
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
A section only applies its settings (including `pageNumbering`) when it starts a new page: content ending with
|
|
182
|
+
`pageBreak: 'after'` before a section leaves an empty page, and the section's settings are ignored.
|
|
183
|
+
|
|
184
|
+
## 9. Table of contents, links, references
|
|
185
|
+
|
|
186
|
+
```js
|
|
187
|
+
{ toc: { title: { text: 'สารบัญ', style: 'title' }, indent: 20, outlines: true } },
|
|
188
|
+
{ text: 'บทที่ 1', style: 'h1', tocItem: true, id: 'ch1' },
|
|
189
|
+
{ text: '1.1 ความเป็นมา', style: 'h2', tocItem: true, tocLevel: 2 },
|
|
190
|
+
{ text: ['ดูหน้า ', { pageReference: 'ch1' }] },
|
|
191
|
+
{ text: 'ไปบทที่ 1', linkToDestination: 'ch1' },
|
|
192
|
+
{ text: 'ไปหน้า 3', linkToPage: 3 },
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
`tocLevel` (w-pdfmaker, default 1) indents the entry by `(tocLevel - 1) × indent` (default 20pt) and, with
|
|
196
|
+
`outlines: true`, nests its bookmark under the previous entry of a lower level. A wrapped entry has its page number on
|
|
197
|
+
the first line. There are no dot leaders. More lists (สารบัญตาราง, สารบัญภาพ): `toc: { id: 'tables' }` with
|
|
198
|
+
`tocItem: 'tables'`. Page numbers follow the section's `pageNumbering` (section 8).
|
|
199
|
+
|
|
200
|
+
`toc` options:
|
|
201
|
+
|
|
202
|
+
| Option | Meaning |
|
|
203
|
+
|---|---|
|
|
204
|
+
| `title` | content above the list |
|
|
205
|
+
| `id` | name of a separate list; entries join it with `tocItem: '<id>'` |
|
|
206
|
+
| `outlines` | also add PDF bookmarks, nested by `tocLevel` |
|
|
207
|
+
| `indent` | pt per level below 1 (default 20) |
|
|
208
|
+
| `textStyle`, `numberStyle`, `textMargin` | style of the entry texts / page numbers, margin of each entry |
|
|
209
|
+
| `hideEmpty` | leave out the whole list, title included, when it has no entries |
|
|
210
|
+
| `sortBy: 'title'`, `sortLocale: 'th'` | alphabetical order instead of page order (e.g. an index) |
|
|
211
|
+
|
|
212
|
+
Entry options on the heading node: `tocItem` (`true`, a list id, or an array such as `[true, 'tables']` for several
|
|
213
|
+
lists), `tocLevel`, `tocStyle` (e.g. `{ bold: true }` for chapters), `tocNumberStyle`, `tocMargin`.
|
|
214
|
+
`{ textReference: 'id' }` prints the text of the node with that `id`.
|
|
215
|
+
|
|
216
|
+
Text nodes can also add PDF bookmarks: `outline: true` (with `outlineText`, `outlineParentId`).
|
|
217
|
+
|
|
218
|
+
## 10. Canvas and QR codes
|
|
219
|
+
|
|
220
|
+
```js
|
|
221
|
+
{ canvas: [
|
|
222
|
+
{ type: 'line', x1: 0, y1: 0, x2: 200, y2: 0, lineWidth: 0.5, dash: { length: 2 } }, // dotted line to sign on
|
|
223
|
+
{ type: 'rect', x: 0, y: 10, w: 100, h: 40, r: 4, lineColor: '#333' },
|
|
224
|
+
{ type: 'ellipse', x: 50, y: 80, r1: 20, r2: 20, color: '#eee' },
|
|
225
|
+
{ type: 'polyline', points: [{ x: 0, y: 0 }, { x: 10, y: 10 }], closePath: true },
|
|
226
|
+
] }
|
|
227
|
+
|
|
228
|
+
{ qr: 'https://example.com/verify/123', fit: 80, eccLevel: 'M' }
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
## 11. Metadata and security
|
|
232
|
+
|
|
233
|
+
```js
|
|
234
|
+
info: { title, author, subject, keywords, creator, producer, creationDate, modDate },
|
|
235
|
+
ownerPassword: 'secret', // lock permissions only (opens without a password)
|
|
236
|
+
userPassword: 'open-me', // password required to open
|
|
237
|
+
permissions: { printing: 'highResolution', modifying: false, copying: false, annotating: false },
|
|
238
|
+
version: '1.7ext3', // PDF version; ext3 gives AES-256 encryption
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
`merge` / `stamp` can open files with only an owner password, and their output is unencrypted.
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Images and SVG
|
|
2
|
+
|
|
3
|
+
## Sources
|
|
4
|
+
|
|
5
|
+
`image` takes JPEG or PNG; `svg` takes SVG. Either can be given directly in the node or by a name from the
|
|
6
|
+
`images` dictionary:
|
|
7
|
+
|
|
8
|
+
| Source | `image` / `images` entry | `svg` |
|
|
9
|
+
|---|---|---|
|
|
10
|
+
| File path | `'/srv/app/assets/logo.png'` (Node) | `'/srv/app/assets/seal.svg'` |
|
|
11
|
+
| Name in `images` | `'logo'` | `'seal'` (entry is an `.svg` path or URL) |
|
|
12
|
+
| Data URL | `'data:image/png;base64,...'` | — |
|
|
13
|
+
| Binary | `Buffer`, `Uint8Array`, `ArrayBuffer` as an `images` entry | — |
|
|
14
|
+
| SVG markup | — | `'<svg ...>...</svg>'` (or an `SVGElement` in the browser) |
|
|
15
|
+
| URL (in `images` only) | `'https://...'` or `{ url, headers, cache }` | same, then `svg: 'name'` |
|
|
16
|
+
|
|
17
|
+
- An `image` whose path or URL ends with `.svg` is drawn as `svg` automatically.
|
|
18
|
+
- A `svg` string that does not start with `<` is treated as a file path or a name in `images`.
|
|
19
|
+
- Formats other than JPEG / PNG / SVG (GIF, WebP, HEIC) are not supported; convert them first.
|
|
20
|
+
- PNG transparency works. JPEG EXIF orientation is applied.
|
|
21
|
+
- SVG needs a size: its own `width` / `height` / `viewBox`, or `width` / `height` / `fit` on the node.
|
|
22
|
+
|
|
23
|
+
Sizing: `width`, `height` (both given on a JPEG/PNG = stretched; SVG keeps its ratio), `fit: [w, h]` (keep ratio
|
|
24
|
+
inside the box), and for `image` only `cover: { width, height, align, valign }` (fill the box and crop) and
|
|
25
|
+
`opacity`. Both accept `alignment`, `margin` and `link`.
|
|
26
|
+
|
|
27
|
+
Use `images` when the same picture appears more than once (it is embedded once) or comes from a URL.
|
|
28
|
+
|
|
29
|
+
## File paths (Node)
|
|
30
|
+
|
|
31
|
+
- Relative paths resolve against `process.cwd()`, which differs between `npm run`, tests, Docker and PM2. Build
|
|
32
|
+
absolute paths from the source file: `path.join(__dirname, '../assets/logo.png')`.
|
|
33
|
+
- Reading local files is allowed by default. To restrict it (e.g. when paths come from users), allow every folder
|
|
34
|
+
the documents read from. The policy also covers **font files**, and in Node the bundled Thai fonts are files in the
|
|
35
|
+
package's `fonts` folder, so leaving it out makes every document with text fail:
|
|
36
|
+
|
|
37
|
+
```js
|
|
38
|
+
const pkgDir = path.dirname(require.resolve('@wirabyte/w-pdfmaker/package.json'));
|
|
39
|
+
const allowed = [path.join(pkgDir, 'fonts'), path.join(__dirname, '../assets'), '/srv/app/uploads']
|
|
40
|
+
.map(dir => path.resolve(dir) + path.sep);
|
|
41
|
+
pdfmake.setLocalAccessPolicy(file => allowed.some(dir => path.resolve(file).startsWith(dir)));
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
(In ESM, get `require` from `createRequire(import.meta.url)`.) A denied path throws `Access to local file denied
|
|
45
|
+
by resource access policy: <path>`. The policy applies to fonts, images, `svg` files and paths given to
|
|
46
|
+
`merge` / `stamp`.
|
|
47
|
+
|
|
48
|
+
## URLs
|
|
49
|
+
|
|
50
|
+
Only entries of the `images` dictionary are downloaded (before layout). In Node, downloads are **blocked by
|
|
51
|
+
default** to prevent SSRF; allow specific hosts:
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
pdfmake.setUrlAccessPolicy(url => url.startsWith('https://files.example.com/'));
|
|
55
|
+
const doc = {
|
|
56
|
+
images: { photo: { url: 'https://files.example.com/p/123.jpg', headers: { Authorization: `Bearer ${token}` } } },
|
|
57
|
+
content: [{ image: 'photo', width: 120 }],
|
|
58
|
+
};
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`cache: true` on an entry (or `pdfmake.setUrlResourceCaching(true)`) keeps the download for later documents;
|
|
62
|
+
`pdfmake.clearUrlResourceCache()` clears it. A failed download is reported when a node uses that image, with the
|
|
63
|
+
URL and HTTP status in the message; unused entries do not fail the document.
|
|
64
|
+
|
|
65
|
+
## Missing images: `fallback`
|
|
66
|
+
|
|
67
|
+
```js
|
|
68
|
+
{ image: user.signaturePath ?? '', fallback: true, width: 100, height: 40 }
|
|
69
|
+
{ svg: 'stamp', fallback: true, width: 60, height: 60 } // images: { stamp: maybeUrl }
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
With `fallback: true` the node becomes empty space instead of failing the document when the image is missing:
|
|
73
|
+
empty value (`''`, `null`, `undefined`, or an empty `images` entry), file not found, or download failed (any non-2xx
|
|
74
|
+
status or network error). It still throws when an access policy denies the file or URL, or when the file exists but
|
|
75
|
+
is not a valid image, so configuration and data bugs stay visible.
|
|
76
|
+
|
|
77
|
+
The empty space has no aspect ratio: give **both** `width` and `height` to reserve the right space. With only
|
|
78
|
+
`width` the space is square; with no size it is 1pt. In TypeScript, `image` is typed `string`, hence `?? ''`.
|
|
79
|
+
|
|
80
|
+
## Browser
|
|
81
|
+
|
|
82
|
+
There is no file system. A path such as `'img/logo.png'` or `'/assets/logo.png'` in `image`, `svg` or `images` is a
|
|
83
|
+
URL relative to the page (`document.baseURI`), downloaded before layout under `setUrlAccessPolicy` (allow-all by
|
|
84
|
+
default in the browser). The page must be served over http(s).
|
|
85
|
+
|
|
86
|
+
- With a bundler (Vite, webpack), pass the URL the bundler gives you, not a source path:
|
|
87
|
+
`import logoUrl from './logo.png'` then `{ image: logoUrl }`.
|
|
88
|
+
- Header, footer and background **functions** run after downloads finish, so a path used only there is never
|
|
89
|
+
fetched. Put it in `images` and refer to it by name.
|
|
90
|
+
- Files added with `pdfmake.addVirtualFileSystem({ 'logo.png': base64 })` are used by name and not downloaded.
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# merge and stamp
|
|
2
|
+
|
|
3
|
+
Both work in Node and the browser, take PDF data or file paths, and return `Promise<Buffer>` (in the browser a
|
|
4
|
+
`Uint8Array`-compatible Buffer). They use a bundled `@cantoo/pdf-lib`; projects do not need `pdf-lib` themselves.
|
|
5
|
+
|
|
6
|
+
A PDF source is `Buffer` / `Uint8Array` / `ArrayBuffer`, or a string **path** (Node: file, relative to
|
|
7
|
+
`process.cwd()`, under `setLocalAccessPolicy`; browser: URL relative to the page, under `setUrlAccessPolicy`).
|
|
8
|
+
A string is never treated as base64; decode base64 to a Buffer first.
|
|
9
|
+
|
|
10
|
+
## merge(parts)
|
|
11
|
+
|
|
12
|
+
```js
|
|
13
|
+
const out = await pdfmake.merge([
|
|
14
|
+
cover, // whole PDF
|
|
15
|
+
{ pdf: report, from: 2, to: 5 }, // pages 2–5, numbered from 1, both included
|
|
16
|
+
path.join(dir, 'appendix.pdf'), // whole file by path
|
|
17
|
+
]);
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
- `from` defaults to 1, `to` to the last page. A range past the last page is cut there; a range starting after the
|
|
21
|
+
last page selects nothing (no error), which is what "the rest of the document after page N" needs when N is the
|
|
22
|
+
last page.
|
|
23
|
+
- Page numbers must be whole numbers ≥ 1, otherwise it throws. If no page is selected at all, it throws
|
|
24
|
+
`merge() selected no pages`.
|
|
25
|
+
- The same PDF can appear several times (split around other parts); its fonts and images are copied once.
|
|
26
|
+
- Page sizes and rotations are kept per page (an A5 landscape attachment stays A5 landscape).
|
|
27
|
+
- Bookmarks, forms and metadata of the inputs are not carried over.
|
|
28
|
+
|
|
29
|
+
### Recipe: attachments after page N, then page numbers over everything
|
|
30
|
+
|
|
31
|
+
```js
|
|
32
|
+
const main = await pdfmake.createPdf(doc).getBuffer();
|
|
33
|
+
const merged = await pdfmake.merge([
|
|
34
|
+
{ pdf: main, to: n },
|
|
35
|
+
...attachmentPaths, // or Buffers
|
|
36
|
+
{ pdf: main, from: n + 1 },
|
|
37
|
+
]);
|
|
38
|
+
const numbered = await pdfmake.stamp(merged, ({ pageNumber, pageCount, height }) => ({
|
|
39
|
+
absolutePosition: { x: 0, y: height - 40 }, // bottom of each page (landscape pages too)
|
|
40
|
+
stack: [{ text: `หน้า ${pageNumber}/${pageCount}`, alignment: 'right', margin: [0, 0, 40, 0] }],
|
|
41
|
+
fontSize: 14,
|
|
42
|
+
}));
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
For the top of the page use `y: 20`; for the bottom centre use `alignment: 'center'` and no margin.
|
|
46
|
+
|
|
47
|
+
## stamp(pdf, fn)
|
|
48
|
+
|
|
49
|
+
Draws pdfmake content over each page of an existing PDF. `fn` is called once per page:
|
|
50
|
+
|
|
51
|
+
```js
|
|
52
|
+
await pdfmake.stamp(pdf, async ({ pageNumber, pageCount, width, height }) => {
|
|
53
|
+
if (pageNumber === 1) return null; // null / undefined: leave the page untouched
|
|
54
|
+
return { text: 'สำเนาถูกต้อง', absolutePosition: { x: width - 150, y: height - 60 }, color: 'red' };
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- `width` / `height` are the page **as shown** in pt: the visible area (CropBox), swapped for pages rotated 90° /
|
|
59
|
+
270°. Coordinates start at the top-left of the page as shown and the page has no margins, so `absolutePosition`
|
|
60
|
+
works the same on rotated pages.
|
|
61
|
+
- `margin` on the node that has `absolutePosition` is ignored. To keep text off the right edge, position a
|
|
62
|
+
full-width wrapper at `x: 0` and put `alignment: 'right'` and the margin on the inner node (recipe above); this also
|
|
63
|
+
works without knowing the text's width.
|
|
64
|
+
- The content is normal pdfmake content (Thai fonts, 16pt default, `distribute`, images by path, `fallback`...) and
|
|
65
|
+
must fit on its page; overflowing content throws `Content returned to stamp() must fit on its page.`
|
|
66
|
+
- Returning the same object for every page is fine (stamp copies it per page).
|
|
67
|
+
- The function may be async (e.g. fetch a per-page QR code).
|
|
68
|
+
- The original page content, bookmarks, forms and metadata are kept, except for owner-locked files (below).
|
|
69
|
+
|
|
70
|
+
### Recipe: watermark on every page
|
|
71
|
+
|
|
72
|
+
```js
|
|
73
|
+
await pdfmake.stamp(pdf, ({ width, height }) => ({
|
|
74
|
+
text: 'ร่าง', fontSize: 120, bold: true, color: '#cc0000', opacity: 0.15,
|
|
75
|
+
absolutePosition: { x: width / 2 - 120, y: height / 2 - 80 },
|
|
76
|
+
}));
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### Recipe: signature image on the last page
|
|
80
|
+
|
|
81
|
+
```js
|
|
82
|
+
await pdfmake.stamp(pdf, ({ pageNumber, pageCount }) => pageNumber === pageCount
|
|
83
|
+
? { image: signaturePath ?? '', fallback: true, width: 120, height: 50, absolutePosition: { x: 380, y: 680 } }
|
|
84
|
+
: null);
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Encrypted PDFs
|
|
88
|
+
|
|
89
|
+
- **Owner password only** (opens without a password, but printing/copying is restricted): both functions open it.
|
|
90
|
+
The output is **not encrypted**, so the original restrictions are gone. `stamp` on such a file rebuilds it from
|
|
91
|
+
copies of its pages, so its bookmarks and forms are lost.
|
|
92
|
+
- **User password** (needs a password to open): both throw an error mentioning `NEEDS PASSWORD`.
|
|
93
|
+
- The output of `merge` / `stamp` is never encrypted, and there is no option to encrypt it. Only documents made
|
|
94
|
+
directly by `createPdf` can be encrypted (`ownerPassword`, `userPassword`, `permissions`).
|