pdf-kalem 0.0.0-stage → 0.1.1

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 (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +343 -2
  3. package/dist/Page-DqmtN2a2.d.ts +37 -0
  4. package/dist/PdfDoc-KL5rp6kh.d.ts +132 -0
  5. package/dist/PdfRenderContext-DW6IqQ5q.d.ts +131 -0
  6. package/dist/Table-_ld_cPdR.d.ts +146 -0
  7. package/dist/aspect-fit-C6ERLMZW.d.ts +80 -0
  8. package/dist/chunk-4JABW7CO.js +1088 -0
  9. package/dist/chunk-4JABW7CO.js.map +1 -0
  10. package/dist/chunk-4RZQEYIL.js +1638 -0
  11. package/dist/chunk-4RZQEYIL.js.map +1 -0
  12. package/dist/chunk-AYT6JHLZ.js +74 -0
  13. package/dist/chunk-AYT6JHLZ.js.map +1 -0
  14. package/dist/chunk-B3LBPGQP.js +112 -0
  15. package/dist/chunk-B3LBPGQP.js.map +1 -0
  16. package/dist/chunk-FMU2QMVG.js +58 -0
  17. package/dist/chunk-FMU2QMVG.js.map +1 -0
  18. package/dist/chunk-IAF6RHAY.js +305 -0
  19. package/dist/chunk-IAF6RHAY.js.map +1 -0
  20. package/dist/chunk-PMF5IICV.js +451 -0
  21. package/dist/chunk-PMF5IICV.js.map +1 -0
  22. package/dist/doc-sizes-B1rAm5Po.d.ts +428 -0
  23. package/dist/edit.d.ts +104 -0
  24. package/dist/edit.js +139 -0
  25. package/dist/edit.js.map +1 -0
  26. package/dist/index.d.ts +187 -0
  27. package/dist/index.js +131 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/internals.d.ts +109 -0
  30. package/dist/internals.js +17 -0
  31. package/dist/internals.js.map +1 -0
  32. package/dist/markdown.d.ts +132 -0
  33. package/dist/markdown.js +412 -0
  34. package/dist/markdown.js.map +1 -0
  35. package/dist/styles-D_iMmh07.d.ts +43 -0
  36. package/dist/types-CWGD5wJk.d.ts +31 -0
  37. package/dist/utils/color-utils.d.ts +15 -0
  38. package/dist/utils/color-utils.js +13 -0
  39. package/dist/utils/color-utils.js.map +1 -0
  40. package/dist/widgets.d.ts +720 -0
  41. package/dist/widgets.js +374 -0
  42. package/dist/widgets.js.map +1 -0
  43. package/package.json +89 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 A Laypanov
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,3 +1,344 @@
1
- # Temporary Holding Version
1
+ # pdf-kalem
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
+ > **For AI assistants:** read [`CONTEXT.md`](./CONTEXT.md) for a compact codebase orientation before diving into the source.
4
+
5
+ > **Status: early alpha.** The API is not yet stable and may change between versions. Not recommended for production use yet — feedback and bug reports are welcome.
6
+
7
+ pdf-kalem is a widget-tree UI library for document-style layout and generation.
8
+
9
+ The core idea is to describe content as a tree of widgets — pages, containers, rows, columns, text, images, links, tables, and SVG paths — run [Yoga](https://github.com/facebook/yoga) for flexbox layout, and render the tree through a backend-specific renderer. The PDF backend (`pdf-lib`).
10
+
11
+ The design is heavily inspired by [Flutter](https://flutter.dev)'s widget-tree model — the idea of composing documents from declarative widget trees with flexbox layout, theme tokens, and per-widget overrides. pdf-kalem adapts that mental model to the document/PDF domain.
12
+
13
+ ## What It Does
14
+
15
+ - Builds page-based layouts with Yoga (flexbox: `Row`, `Column`, `gap`, `flexGrow`, `%` widths, absolute positioning).
16
+ - **Pagination**: content taller than one page automatically flows onto additional pages. Text blocks split by line, table rows stay whole and headers repeat, and each `Page` re-renders its chrome per output page. Opt out per page with `Page({ overflow: false })` or keep a text block together with `Text(..., { breakable: false })`.
17
+ - **Edits existing PDFs** via `pdf-kalem/edit`: load a PDF as Page widgets, overlay widgets on its pages, restructure/merge, save — original content, annotations, and form fields preserved.
18
+ - Exports PDFs through `pdf-lib` with metadata, custom fonts, link annotations, and SVG paths.
19
+ - Provides a shared text engine (powered by [`@chenglou/pretext`](https://github.com/chenglou/pretext)) with grapheme-aware wrapping, `maxLines`, and `ellipsis` overflow.
20
+ - Supports document-scoped themes (color tokens, font aliases, text variants, table/container defaults) with per-widget overrides.
21
+ - Runs in browser and Node (output helpers: `save`, `getBlob`, `download`, `getBuffer`, `writeToFile`).
22
+
23
+ ## Architecture
24
+
25
+ The project is split into three layers:
26
+
27
+ 1. **Widget tree** — `PdfDoc`, `Page`, `Container`, `Text`, `Row`, `Column`, `Image`, `Link`, `FixedContainer`, `SVGPath`, `Table`, `HLine`, and related layout primitives. Widgets depend on a backend-neutral `RenderContext` interface, not on any concrete backend.
28
+ 2. **Render layer** — `PdfRenderContext` (implements `RenderContext`) drives `pdf-lib`; `PdfRenderer` walks the page tree and drives the context. The PDF coordinate flip (y grows up from the bottom-left) is applied inside `PdfRenderContext`, so widgets deal in layout boxes, not PDF math.
29
+ 3. **Shared services** — `FontRegistry` (singleton) owns registered font bytes, the fontkit instance, and browser `FontFace` loading. `TextLayoutEngine` (pure text measurement/wrapping/truncation) and `TextPainter` (draws a laid-out text block via a `RenderContext`) are shared by `Text` and `Link`.
30
+
31
+ `PdfDoc` is the document model: it owns the page tree, theme, metadata, and lifecycle hooks. It is intentionally **not** a `Widget` — a document is not a layout node. Rendering is delegated to `PdfRenderer`, and runtime helpers (`save`/`getBlob`/`download`/`getBuffer`/`writeToFile`) live on `PdfDoc` as convenience methods.
32
+
33
+ ## Install
34
+
35
+ From npm:
36
+
37
+ ```bash
38
+ pnpm add pdf-kalem
39
+ ```
40
+
41
+ For local development in this repository:
42
+
43
+ ```bash
44
+ pnpm install
45
+ ```
46
+
47
+ ## Examples
48
+
49
+ The [`examples/`](./examples) folder holds self-contained, copyable projects — a one-file hello-world, an invoice, a multi-page report, and a markdown-to-PDF CLI. Each is a plain ESM TypeScript folder (no per-example npm setup) with its own theme, components, and data, structured so you can lift one into your own project and adapt it:
50
+
51
+ ```bash
52
+ pnpm build # examples import the built library
53
+ pnpm examples # run every example; each writes its PDF next to its code
54
+ ```
55
+
56
+ See [`examples/README.md`](./examples/README.md) for what each one demonstrates and how to copy one.
57
+
58
+ ## Build
59
+
60
+ ```bash
61
+ pnpm build
62
+ ```
63
+
64
+ `pnpm build` emits the publishable library into `dist/`.
65
+
66
+ ## Docs
67
+
68
+ ```bash
69
+ pnpm docs:dev
70
+ ```
71
+
72
+ `pnpm docs:dev` runs the VitePress documentation site (Vue 3 + UnoCSS, in `docs/`) with a guide and dedicated playground pages for the widget-tree API and the markdown converter (both playgrounds are live workbenches). `pnpm docs:build` emits the static site into `docs/.vitepress/dist/`.
73
+
74
+ ## Example
75
+
76
+ ```ts
77
+ import {
78
+ PdfDoc,
79
+ PageSize,
80
+ } from 'pdf-kalem';
81
+ import { Page, Text, Container } from 'pdf-kalem/widgets';
82
+ import { fromHex } from 'pdf-kalem/utils/color-utils';
83
+
84
+ const doc = new PdfDoc({
85
+ size: PageSize.LETTER,
86
+ children: [
87
+ Page({
88
+ padding: 24,
89
+ children: [
90
+ Text('Hello world', { size: 18 }),
91
+ Container({
92
+ width: 200,
93
+ height: 80,
94
+ bgColor: fromHex('#FFCC00'),
95
+ }),
96
+ ],
97
+ }),
98
+ ],
99
+ });
100
+
101
+ const pdfBytes = await doc.save();
102
+ ```
103
+
104
+ Additional output helpers are available when you want a runtime-specific result:
105
+
106
+ ```ts
107
+ const bytes = await doc.save();
108
+ const blob = await doc.getBlob();
109
+ await doc.download('invoice.pdf');
110
+ await doc.print(); // browser print dialog
111
+ const buffer = await doc.getBuffer();
112
+ await doc.writeToFile('invoice.pdf');
113
+ ```
114
+
115
+ `getBuffer()` and `writeToFile()` are intended for Node runtimes. `download()`, `getBlob()`, and `print()` are browser-only — `print()` loads the PDF into a hidden iframe and opens the browser's print dialog (Safari's PDF viewer doesn't support programmatic printing; download-and-print manually there).
116
+
117
+ ### Pagination
118
+
119
+ When a page's content is taller than the page, pdf-kalem splits it across additional pages. It does this with a three-pass approach (layout → paginate → render), similar to react-pdf:
120
+
121
+ 1. **Layout** — the whole page tree is laid out once on a single tall canvas.
122
+ 2. **Paginate** — the laid-out tree is walked and split into per-page *fragment* trees. Each fragment is a lightweight view onto a widget for one output page (it reuses the same Yoga node, so there's no re-layout).
123
+ 3. **Render** — each output page adds a PDF page and renders its fragments, shifting coordinates by `-pageIndex × pageHeight` so each slice lands correctly.
124
+
125
+ Splitting rules by widget:
126
+
127
+ - **Text** splits line-by-line (`breakable: true` by default). Use `{ breakable: false }` to keep a block together.
128
+ - **Table rows** stay whole (never split mid-row), and the **header repeats** on each page that shows body rows.
129
+ - **Containers/columns** pass the boundary to their children.
130
+
131
+ ```ts
132
+ Page({
133
+ padding: 24,
134
+ children: [
135
+ Text(longReport, { variant: 'body' }), // flows across pages by line
136
+ Table.fromRows(rows, { header: true }), // rows stay whole, header repeats
137
+ ],
138
+ });
139
+ ```
140
+
141
+ To disable pagination for a page (legacy single-page, overflow is clipped):
142
+
143
+ ```ts
144
+ Page({ overflow: false, children: [...] });
145
+ ```
146
+
147
+ ### Tables
148
+
149
+ For the common case of a table where every cell is plain text, use `Table.fromRows`:
150
+
151
+ ```ts
152
+ import { Table, Text } from 'pdf-kalem/widgets';
153
+
154
+ Table.fromRows(
155
+ [
156
+ ['KPI', 'Value', 'Change'],
157
+ ['Quarterly revenue', '$42k', '+12%'],
158
+ ['Customer retention', '93%', '+4%'],
159
+ ],
160
+ {
161
+ width: '100%',
162
+ columnWeights: [2, 1, 1],
163
+ header: true,
164
+ }
165
+ );
166
+ ```
167
+
168
+ Cells accept either strings (auto-wrapped in `Text`) or arbitrary widgets for custom content. For full control over headers, cell padding, or mixed cell content, use the explicit `Table`/`TableHead`/`TableBody`/`TableRow`/`TableCell` constructors.
169
+
170
+ ### Rich text (runs)
171
+
172
+ `Text` accepts an array of styled runs instead of a plain string. Each run carries its own style flags, which combine with the text's base font:
173
+
174
+ ```ts
175
+ import { Text, Link } from 'pdf-kalem/widgets';
176
+
177
+ Text(
178
+ [
179
+ { text: 'Revenue grew ' },
180
+ { text: '12%', bold: true },
181
+ { text: ' quarter over quarter' },
182
+ { text: ' (audited)', italic: true, color: '#666666' },
183
+ ],
184
+ { size: 12 }
185
+ );
186
+
187
+ // Runs can carry their own links — each line fragment of the run gets its
188
+ // own clickable annotation, so a run that wraps stays clickable everywhere.
189
+ Text([{ text: 'Read the ' }, { text: 'full report', href: 'https://example.com' }]);
190
+
191
+ // `mono` switches the run to the builtin monospace family; `font` overrides
192
+ // the family outright (theme token or family name).
193
+ Text([{ text: 'const x = 1', mono: true }]);
194
+ ```
195
+
196
+ Run flags: `bold`, `italic`, `strike`, `href`, `mono`, `font`, `color`. Faces resolve through the run's family with the usual fallback chain, so `{ bold: true }` in an `inter` text uses `inter-bold` when loaded and falls back with a warning otherwise. Words that span run boundaries (`he` + `**llo**`) never break internally; wrapping, `maxLines`, and `ellipsis` all work across runs.
197
+
198
+ ## Fonts
199
+
200
+ Built-in aliases work without registration: `sans`, `sans-bold`, `sans-italic`, `sans-bold-italic`, `serif` (+ variants), `mono` (+ variants).
201
+
202
+ For real typography, load a font set once and pass it to the document. Families come from your own font files — the repo's examples load Inter this way (the OFL-licensed TTFs live in [`examples/fonts/`](./examples/fonts)):
203
+
204
+ ```ts
205
+ import { PdfDoc, useFonts } from 'pdf-kalem';
206
+
207
+ const fonts = await useFonts(
208
+ { body: 'inter' },
209
+ { files: { inter: { regular: interBytes, bold: interBoldBytes } } },
210
+ );
211
+
212
+ const doc = new PdfDoc({ fonts, children: [/* ... */] });
213
+ ```
214
+
215
+ A family entry is either a single source (its regular face) or an object of per-face sources; a string is fetched (browser/http URL — pass bytes for Node filesystem loading). Code falls back to the builtin `mono` alias (Courier); load a real mono family via `files` when you need one.
216
+
217
+ A family carries faces: `regular` plus optional `bold`, `italic`, and `boldItalic`. A face is referenced by suffixing the family name — `inter-bold`, `inter-italic`, `inter-bold-italic` — the same convention the builtin aliases use. Missing faces fall back at embed time (bold-italic → bold → italic → regular) with a console warning, so a family can ship incrementally.
218
+
219
+ Bring your own fonts per face:
220
+
221
+ ```ts
222
+ const fonts = await useFonts(
223
+ { body: 'inter' },
224
+ {
225
+ files: {
226
+ inter: { bold: '/fonts/MyInter-Bold.ttf' }, // one face as a URL
227
+ 'my-serif': {
228
+ regular: '/fonts/MySerif.ttf',
229
+ italic: '/fonts/MySerif-Italic.ttf',
230
+ },
231
+ },
232
+ },
233
+ );
234
+ ```
235
+
236
+ No `registerFontkit` call is needed — fontkit loads lazily on the first custom-font embed. Legacy global registration (`PdfDoc.registerFont` / `registerFonts` / `registerFontFromUrl`) still works as a process-wide fallback; doc-scoped `FontSet`s always resolve first.
237
+
238
+ ## Markdown
239
+
240
+ The `pdf-kalem/markdown` subpath converts markdown (GFM, powered by [`marked`](https://github.com/markedjs/marked)) into widgets or a ready-to-save document:
241
+
242
+ ```ts
243
+ import { markdownToPdf, markdownToWidgets } from 'pdf-kalem/markdown';
244
+
245
+ // Sugar: one paginated Page, markdown theme defaults merged under your theme.
246
+ const doc = await markdownToPdf('# Report\n\nBody text with **emphasis**.', {
247
+ theme: myTheme, // optional — user values win over the defaults
248
+ fonts, // optional FontSet (see Fonts above)
249
+ page: { padding: 48 },
250
+ });
251
+ await doc.save();
252
+
253
+ // Deep seam: bare blocks you embed in your own Page (wrap in a Column with a
254
+ // gap for spacing).
255
+ const blocks = await markdownToWidgets(md, { styles: { spacing: 8 } });
256
+ ```
257
+
258
+ Supported: headings (`h1`..`h6` theme variants, bold), emphasis (`**bold**`, `*italic*`, `~~strikethrough~~`, `` `code` ``), links (clickable per line fragment, underlined, `link` color token), ordered/unordered/nested/task lists (tasks render as `✓`/`□`), fenced code blocks (monospace, `pre-wrap`, background), blockquotes (left rule + italic), GFM tables (per-column alignment, padded cells, header row), horizontal rules, and images (png/jpeg — the format is sniffed from the fetched bytes; other formats are skipped with a warning).
259
+
260
+ Styling is theme-driven: headings resolve the `h1`..`h6` text variants, links resolve the `link` color token, and `MarkdownStyles` overrides the rest (code font/colors, blockquote rule, list indent, spacing, image width, table options). `markdownThemeDefaults` is exported so custom docs can merge the same baseline.
261
+
262
+ A copyable converter project ships in [`examples/markdown/`](./examples/markdown) — a small CLI that turns any markdown file (or an embedded sample) into a paginated PDF.
263
+
264
+ ## Theme
265
+
266
+ You can define document-scoped theme tokens and widget defaults on the document itself.
267
+
268
+ ```ts
269
+ import { PdfDoc, PageSize, createTheme } from 'pdf-kalem';
270
+ import { Page, Text, Table } from 'pdf-kalem/widgets';
271
+ import { fromHex } from 'pdf-kalem/utils/color-utils';
272
+
273
+ const theme = createTheme({
274
+ fonts: {
275
+ body: 'Inter',
276
+ heading: 'Inter',
277
+ },
278
+ colors: {
279
+ text: fromHex('#0f172a'),
280
+ primary: fromHex('#1d4ed8'),
281
+ border: fromHex('#cbd5e1'),
282
+ },
283
+ text: {
284
+ body: { font: 'body', size: 12, color: 'text' },
285
+ h1: { font: 'heading', size: 20, color: 'text' },
286
+ link: { font: 'body', size: 12, color: 'primary', underline: true },
287
+ },
288
+ table: {
289
+ borderColor: 'border',
290
+ headBgColor: 'primary',
291
+ cellPadding: 8,
292
+ },
293
+ });
294
+
295
+ const doc = new PdfDoc({
296
+ size: PageSize.LETTER,
297
+ theme,
298
+ children: [
299
+ Page({
300
+ children: [
301
+ Text('Quarterly report', { variant: 'h1' }),
302
+ Text('Prepared with shared theme defaults', { variant: 'body' }),
303
+ Table({
304
+ width: '100%',
305
+ }),
306
+ ],
307
+ }),
308
+ ],
309
+ });
310
+ ```
311
+
312
+ Widget props still override theme defaults, so the theme can stay focused on typography and visual tokens while layout remains explicit in the document tree.
313
+
314
+ ## Project Status
315
+
316
+ The current direction is:
317
+
318
+ - keep the widget tree focused on document layout
319
+ - keep PDF behavior explicit and first-class via `PdfDoc` / `PdfRenderContext`
320
+ - **PDF-only focus** — no image/HTML backends are planned ([ADR 0001](./docs/adr/0001-pdf-only-focus.md)). PDF-specific features live in PDF-typed modules (e.g. `pdf-kalem/edit`) instead of widening the backend-neutral interface.
321
+
322
+ The `RenderContext` seam stays because it is load-bearing, not as a backend hook: pagination's per-page `PageScope` composes through it, and the PDF Y-flip lives in one place (`mapContentBox`).
323
+
324
+ ## Scripts
325
+
326
+ - `pnpm build` builds the npm package into `dist/`.
327
+ - `pnpm examples` builds the package and runs every example (each writes its PDF next to its code).
328
+ - `pnpm typecheck` runs TypeScript without emitting files.
329
+ - `pnpm docs:dev` runs the documentation site.
330
+
331
+ ## Special Thanks
332
+
333
+ pdf-kalem stands on the shoulders of several excellent open-source projects:
334
+
335
+ - [Flutter](https://flutter.dev) — the widget-tree mental model that inspired pdf-kalem's design.
336
+ - [pdf-lib](https://github.com/Hopding/pdf-lib) — the PDF generation engine that powers the PDF backend.
337
+ - [Yoga](https://github.com/facebook/yoga) — the flexbox layout engine (from Meta/Facebook) that handles all layout computation.
338
+ - [`@chenglou/pretext`](https://github.com/chenglou/pretext) — the grapheme-aware text measurement and wrapping engine.
339
+ - [@mdi/js](https://github.com/Templarian/MaterialDesign-JS) — Material Design Icons path data, used by the `Icon` widget.
340
+ - [@pdf-lib/fontkit](https://github.com/Hopding/pdf-lib/tree/master/fontkit) — custom font subsetting and embedding for PDFs.
341
+
342
+ # Tools
343
+ - Zed Editor
344
+ - GLM LLM Model
@@ -0,0 +1,37 @@
1
+ import { W as Widget, t as WidgetOptions, e as PageSize, R as RenderContext, s as LayoutBox } from './doc-sizes-B1rAm5Po.js';
2
+
3
+ interface PageOptions extends WidgetOptions {
4
+ padding?: number;
5
+ size?: PageSize;
6
+ dimensions?: [number, number];
7
+ children?: Widget[];
8
+ /**
9
+ * When true (default), content taller than one page is split across
10
+ * additional output pages. Set to false to render a single page and let
11
+ * overflow be clipped by the viewer.
12
+ */
13
+ overflow?: boolean;
14
+ }
15
+ declare class PageWidget extends Widget {
16
+ private dimensions?;
17
+ private size?;
18
+ private readonly paginateContent;
19
+ constructor(options?: PageOptions);
20
+ getDimensions(context: RenderContext): [number, number];
21
+ /** Whether content overflowing this page splits across continuation pages. */
22
+ get paginates(): boolean;
23
+ /** @internal — flow layout pass for pagination (used by Paginator). */
24
+ runFlowLayout(width: number, height: number | undefined): void;
25
+ /** @internal — content box after layout, page-relative top-left origin. */
26
+ getContentBox(dimensions: [number, number]): LayoutBox;
27
+ /**
28
+ * Opens the backend surface this page paints onto. LoadedPage overrides
29
+ * this to a no-op — its surface is an adopted existing page, opened in
30
+ * render() before the layout pass.
31
+ */
32
+ protected openPage(context: RenderContext, dimensions: [number, number]): Promise<void>;
33
+ render(context: RenderContext): Promise<void>;
34
+ }
35
+ declare function Page(options?: PageOptions): PageWidget;
36
+
37
+ export { PageWidget as P, Page as a };
@@ -0,0 +1,132 @@
1
+ import { e as PageSize, T as Theme, W as Widget, t as WidgetOptions } from './doc-sizes-B1rAm5Po.js';
2
+ import { P as PdfRenderContext } from './PdfRenderContext-DW6IqQ5q.js';
3
+ import { PDFDocument } from 'pdf-lib';
4
+ import { F as FontSet } from './types-CWGD5wJk.js';
5
+
6
+ type Awaitable<T> = T | Promise<T>;
7
+ type NodeBufferLike = Uint8Array;
8
+ interface PdfDocOptions extends WidgetOptions {
9
+ size?: PageSize;
10
+ dimensions?: [number, number];
11
+ layout?: 'portrait' | 'landscape';
12
+ theme?: Theme;
13
+ /**
14
+ * Font families for this document, from {@link useFonts}. Applied over the
15
+ * theme's font mapping at construction (doc-level wins; the theme object
16
+ * is never mutated) and resolved doc-scoped during rendering.
17
+ */
18
+ fonts?: FontSet;
19
+ /** Enables drawing colored debug outlines around every widget. */
20
+ debug?: boolean;
21
+ meta?: PdfDocMeta;
22
+ beforeCreate?: (args: PdfDocBeforeCreateArgs) => Awaitable<void>;
23
+ afterSave?: (args: PdfDocAfterSaveArgs) => Awaitable<void>;
24
+ children?: Widget[];
25
+ }
26
+ interface PdfDocMeta {
27
+ title?: string;
28
+ author?: string;
29
+ subject?: string;
30
+ keywords?: string[];
31
+ language?: string;
32
+ creator?: string;
33
+ producer?: string;
34
+ creationDate?: Date;
35
+ modificationDate?: Date;
36
+ }
37
+ interface PdfDocBeforeCreateArgs {
38
+ context: PdfRenderContext;
39
+ root: PdfDoc;
40
+ }
41
+ interface PdfDocAfterSaveArgs {
42
+ doc: PDFDocument;
43
+ context: PdfRenderContext;
44
+ root: PdfDoc;
45
+ bytes: Uint8Array;
46
+ }
47
+ /**
48
+ * PdfDoc is the document model: it owns the page tree, theme, metadata, and
49
+ * lifecycle hooks. It is intentionally not a Widget — a document is not a
50
+ * layout node. Rendering is delegated to {@link PdfRenderer}, and runtime
51
+ * helpers (blob/download/buffer/file) live on PdfDoc as convenience methods.
52
+ */
53
+ declare class PdfDoc {
54
+ private static globalBeforeCreate;
55
+ private static globalAfterSave;
56
+ /**
57
+ * Registers a font from `url`, stores its bytes in {@link FontRegistry},
58
+ * and loads it into the browser font set (for canvas-based measurement via
59
+ * pretext). Delegates to the shared registry so any future backend
60
+ * (ImageDoc, EmailDoc) sees the same registered fonts.
61
+ */
62
+ static registerFontFromUrl(fontName: string, url: string): Promise<boolean>;
63
+ /**
64
+ * Bulk {@link registerFontFromUrl}. `fonts` maps font name → URL.
65
+ */
66
+ static registerFonts(fonts: Record<string, string>): Promise<void>;
67
+ /**
68
+ * Registers raw font bytes under `fontName`. Delegates to the shared
69
+ * {@link FontRegistry}.
70
+ */
71
+ static registerFont(fontName: string, fontData: Uint8Array | ArrayBuffer): void;
72
+ static registerFontkit(fontkit: any): void;
73
+ static beforeCreate(hook: (args: PdfDocBeforeCreateArgs) => Awaitable<void>): void;
74
+ static afterSave(hook: (args: PdfDocAfterSaveArgs) => Awaitable<void>): void;
75
+ static clearHooks(): void;
76
+ protected size?: PageSize;
77
+ protected dimensions?: [number, number];
78
+ protected layout: 'portrait' | 'landscape';
79
+ protected theme?: Theme;
80
+ protected fonts?: FontSet;
81
+ protected meta?: PdfDocMeta;
82
+ protected beforeCreate?: (args: PdfDocBeforeCreateArgs) => Awaitable<void>;
83
+ protected afterSave?: (args: PdfDocAfterSaveArgs) => Awaitable<void>;
84
+ protected readonly children: Widget[];
85
+ protected readonly context: PdfRenderContext;
86
+ private cachedPageCount?;
87
+ constructor(options?: PdfDocOptions, context?: PdfRenderContext);
88
+ getContext(): PdfRenderContext;
89
+ /**
90
+ * Total number of output pages, computed by running the pagination plan
91
+ * for every Page widget (a dry run: no drawing, no pages added).
92
+ * Memoized — plans are pure, so the count is stable for an unchanged tree.
93
+ *
94
+ * Text metrics are exact once fonts have been embedded by {@link save};
95
+ * before that, un-embedded fonts fall back to estimated widths. Trees
96
+ * containing images need a created document (call after save, e.g. in an
97
+ * `afterSave` hook) because image embedding requires one.
98
+ */
99
+ getPageCount(): Promise<number>;
100
+ getChildren(): Widget[];
101
+ getMeta(): PdfDocMeta | undefined;
102
+ getTheme(): Theme | undefined;
103
+ getFonts(): FontSet | undefined;
104
+ /**
105
+ * The doc's effective theme: the user's theme with the FontSet's font
106
+ * tokens applied over it (doc-level wins). Returns a NEW object — the
107
+ * user's theme value is never mutated, so theme objects can be shared
108
+ * across documents safely.
109
+ */
110
+ private deriveTheme;
111
+ private getDimensions;
112
+ getWidth(): number;
113
+ getHeight(): number;
114
+ savePdf(): Promise<Uint8Array>;
115
+ getBlob(): Promise<Blob>;
116
+ download(fileName?: string): Promise<void>;
117
+ /**
118
+ * Opens the browser's print dialog with the generated PDF: the blob is
119
+ * loaded into a hidden iframe and the iframe's print is triggered once it
120
+ * finishes loading. Browser-only.
121
+ *
122
+ * Known limitation: Safari's PDF viewer doesn't support programmatic
123
+ * printing — the dialog may print blank there. Downloading and printing
124
+ * manually is the reliable fallback.
125
+ */
126
+ print(): Promise<void>;
127
+ getBuffer(): Promise<NodeBufferLike>;
128
+ writeToFile(filePath: string): Promise<void>;
129
+ save(): Promise<Uint8Array>;
130
+ }
131
+
132
+ export { PdfDoc as P, type PdfDocAfterSaveArgs as a, type PdfDocBeforeCreateArgs as b, type PdfDocMeta as c, type PdfDocOptions as d };
@@ -0,0 +1,131 @@
1
+ import { PDFDocument, PDFPage, StandardFonts, PDFFont } from 'pdf-lib';
2
+ import { R as RenderContext, g as RenderContextOptions, T as Theme, W as Widget, h as RenderImage, b as DrawRectangleArgs, d as DrawTextArgs, a as DrawLineArgs, D as DrawImageArgs, c as DrawSvgPathArgs, L as LinkAnnotationArgs } from './doc-sizes-B1rAm5Po.js';
3
+ import { F as FontSet } from './types-CWGD5wJk.js';
4
+
5
+ /**
6
+ * PDF backend for {@link RenderContext}. Drives a `pdf-lib` `PDFDocument`:
7
+ * embeds fonts via fontkit, draws primitives on `PDFPage`, and applies the
8
+ * PDF coordinate flip (y grows up from the bottom-left) in
9
+ * {@link getLayoutBox}.
10
+ *
11
+ * This was previously named `RenderContext`. The rename makes the
12
+ * backend-specific nature explicit and frees the `RenderContext` name for
13
+ * the backend-neutral interface that widgets depend on.
14
+ */
15
+ declare class PdfRenderContext implements RenderContext {
16
+ private options;
17
+ private theme?;
18
+ private doc?;
19
+ private page;
20
+ private dimensions?;
21
+ private fontCache;
22
+ private textWidthCache;
23
+ private fontkitRegisteredOnDoc;
24
+ private fontkitInstance?;
25
+ private fonts?;
26
+ constructor(options: RenderContextOptions);
27
+ setDebug(enabled: boolean): void;
28
+ setTheme(theme?: Theme): void;
29
+ getTheme(): Theme | undefined;
30
+ isDebugEnabled(): boolean;
31
+ getDebugStrokeWidth(): number;
32
+ setDefaultDimensions(width: number, height: number): void;
33
+ getOptions(): RenderContextOptions;
34
+ /**
35
+ * Doc-scoped font families (from `new PdfDoc({ fonts })`). Looked up
36
+ * before the global {@link FontRegistry}, so two documents in one process
37
+ * can use different bytes under the same family name.
38
+ */
39
+ setFonts(fonts?: FontSet): void;
40
+ getFonts(): FontSet | undefined;
41
+ /**
42
+ * @deprecated Font registration is now handled by {@link FontRegistry}.
43
+ * Kept for back-comat; delegates to the shared registry.
44
+ */
45
+ static registerFont(fontName: string, fontData: Uint8Array | ArrayBuffer): void;
46
+ /**
47
+ * @deprecated Fontkit registration is now handled by {@link FontRegistry}.
48
+ * Kept for back-comat; delegates to the shared registry.
49
+ */
50
+ static registerFontkit(fontkit: any): void;
51
+ setDocument(doc: PDFDocument): void;
52
+ getDocument(): PDFDocument;
53
+ addPage(dimensions: [number, number]): PDFPage;
54
+ getCurrentPage(): PDFPage | null;
55
+ setCurrentPage(currentPage: PDFPage): void;
56
+ /**
57
+ * Adopts a page from a foreign `PDFDocument` (e.g. one loaded by the edit
58
+ * module): the page object is copied into this document — content streams,
59
+ * annotations, links, and form fields come along — and becomes the current
60
+ * page, so subsequent drawing lands on top of the original content.
61
+ */
62
+ adoptPage(source: unknown, pageIndex: number): Promise<void>;
63
+ getPageHeight(): number;
64
+ getPageWidth(): number;
65
+ getDimensions(): [number, number];
66
+ /**
67
+ * Maps a top-left-origin, page-relative box into PDF coordinates
68
+ * (bottom-left origin, y grows up). This is the single place the PDF
69
+ * Y-flip lives; {@link getLayoutBox} and the pagination scope both route
70
+ * through it.
71
+ */
72
+ mapContentBox(box: {
73
+ x: number;
74
+ y: number;
75
+ width: number;
76
+ height: number;
77
+ }): {
78
+ x: number;
79
+ y: number;
80
+ width: number;
81
+ height: number;
82
+ };
83
+ /**
84
+ * Returns the widget's layout box in PDF coordinates (bottom-left origin,
85
+ * y grows up). During pagination the per-page `PageScope` answers with
86
+ * plan-driven boxes routed through {@link mapContentBox}; this direct path
87
+ * serves non-paginated rendering (`overflow: false`, fitting documents).
88
+ */
89
+ getLayoutBox(widget: Widget): {
90
+ x: number;
91
+ y: number;
92
+ width: number;
93
+ height: number;
94
+ };
95
+ /** Pagination is not active on the raw backend; the per-page scope answers. */
96
+ getFlowOffset(_widget: Widget): number;
97
+ getFont(fontName?: StandardFonts | string): Promise<PDFFont>;
98
+ /**
99
+ * The fontkit instance used to embed custom fonts: an explicitly
100
+ * registered one (via {@link FontRegistry}) first, then a lazy dynamic
101
+ * import of `@pdf-lib/fontkit` — so documents with custom fonts need no
102
+ * `registerFontkit` call.
103
+ */
104
+ private ensureFontkit;
105
+ preloadFont(fontName?: StandardFonts | string): Promise<void>;
106
+ measureTextWidth(text: string, size: number, fontName?: StandardFonts | string): number;
107
+ /**
108
+ * Typographic (hhea) metrics for embedded custom fonts, via pdf-lib's
109
+ * fontkit embedder. pdf-lib's `heightAtSize` is bbox-based — its
110
+ * `descender: false` variant returns the bbox yMax, which sits far below
111
+ * the real ascender for fonts like Inter and made line boxes bottom-heavy.
112
+ * Standard fonts have no fontkit font; their AFM metrics are already
113
+ * typographic, so the bbox path is correct for them.
114
+ */
115
+ private customFontMetrics;
116
+ measureFontHeight(size: number, fontName?: StandardFonts | string, options?: {
117
+ descender?: boolean;
118
+ }): number;
119
+ measureDefaultLineHeight(size: number, fontName?: StandardFonts | string): number;
120
+ measureFontAscent(size: number, fontName?: StandardFonts | string): number;
121
+ embedImage(bytes: ArrayBuffer, format: 'png' | 'jpeg'): Promise<RenderImage>;
122
+ private requireCurrentPage;
123
+ drawRectangle(args: DrawRectangleArgs): void;
124
+ drawText({ text, x, y, size, color, fontName, maxWidth }: DrawTextArgs): Promise<void>;
125
+ drawLine(args: DrawLineArgs): void;
126
+ drawImage(image: RenderImage, args: DrawImageArgs): void;
127
+ drawSvgPath({ d, ...options }: DrawSvgPathArgs): void;
128
+ addLinkAnnotation({ href, rect }: LinkAnnotationArgs): void;
129
+ }
130
+
131
+ export { PdfRenderContext as P };