@formepdf/core 0.7.6 → 0.7.8
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/dist/browser.d.ts +39 -0
- package/dist/browser.js +203 -0
- package/package.json +6 -2
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser entry point for @formepdf/core.
|
|
3
|
+
*
|
|
4
|
+
* Import as `@formepdf/core/browser` — no Node APIs, works in any
|
|
5
|
+
* modern browser with WebAssembly support.
|
|
6
|
+
*
|
|
7
|
+
* WASM is loaded via fetch() from the same origin as the importing
|
|
8
|
+
* module (using import.meta.url resolution in the wasm-pack glue).
|
|
9
|
+
* Bundlers like Vite, esbuild, and webpack handle this automatically.
|
|
10
|
+
* For script-tag usage, call `initWasm()` with an explicit URL first.
|
|
11
|
+
*/
|
|
12
|
+
import type { InitInput } from '../pkg/forme.js';
|
|
13
|
+
export type { Color, EdgeValues, CornerValues, ElementStyleInfo, ElementInfo, PageInfo, LayoutInfo, RenderWithLayoutResult, RenderDocumentOptions, } from './index.js';
|
|
14
|
+
import type { RenderWithLayoutResult, RenderDocumentOptions } from './index.js';
|
|
15
|
+
/**
|
|
16
|
+
* Initialize the WASM module. Called automatically on first render,
|
|
17
|
+
* but you can call it early to control timing or provide a custom
|
|
18
|
+
* WASM URL/bytes.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* // Auto-resolve (works with bundlers)
|
|
22
|
+
* await initWasm();
|
|
23
|
+
*
|
|
24
|
+
* // Explicit URL (CDN, custom path, etc.)
|
|
25
|
+
* await initWasm('/wasm/forme_bg.wasm');
|
|
26
|
+
* await initWasm(new URL('./forme_bg.wasm', import.meta.url));
|
|
27
|
+
*/
|
|
28
|
+
export declare function init(module?: InitInput | Promise<InitInput>): Promise<void>;
|
|
29
|
+
export declare function renderPdf(json: string): Promise<Uint8Array>;
|
|
30
|
+
export declare function renderPdfWithLayout(json: string): Promise<RenderWithLayoutResult>;
|
|
31
|
+
export declare function renderDocument(element: import('react').ReactElement, options?: RenderDocumentOptions): Promise<Uint8Array>;
|
|
32
|
+
export declare function renderDocumentWithLayout(element: import('react').ReactElement, options?: RenderDocumentOptions): Promise<RenderWithLayoutResult>;
|
|
33
|
+
export declare function renderTemplate(templateJson: string, dataJson: string): Promise<Uint8Array>;
|
|
34
|
+
export declare function renderTemplateWithLayout(templateJson: string, dataJson: string): Promise<RenderWithLayoutResult>;
|
|
35
|
+
/**
|
|
36
|
+
* Extract embedded JSON data from a Forme-generated PDF.
|
|
37
|
+
* Uses the browser-native DecompressionStream API (no node:zlib).
|
|
38
|
+
*/
|
|
39
|
+
export declare function extractData(pdfBytes: Uint8Array): Promise<unknown | null>;
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser entry point for @formepdf/core.
|
|
3
|
+
*
|
|
4
|
+
* Import as `@formepdf/core/browser` — no Node APIs, works in any
|
|
5
|
+
* modern browser with WebAssembly support.
|
|
6
|
+
*
|
|
7
|
+
* WASM is loaded via fetch() from the same origin as the importing
|
|
8
|
+
* module (using import.meta.url resolution in the wasm-pack glue).
|
|
9
|
+
* Bundlers like Vite, esbuild, and webpack handle this automatically.
|
|
10
|
+
* For script-tag usage, call `initWasm()` with an explicit URL first.
|
|
11
|
+
*/
|
|
12
|
+
import initWasm, { render_pdf as wasmRenderPdf, render_pdf_with_layout as wasmRenderPdfWithLayout, render_template_pdf as wasmRenderTemplatePdf, render_template_pdf_with_layout as wasmRenderTemplatePdfWithLayout, } from '../pkg/forme.js';
|
|
13
|
+
// ── WASM initialization ────────────────────────────────────────────
|
|
14
|
+
let initialized = false;
|
|
15
|
+
/**
|
|
16
|
+
* Initialize the WASM module. Called automatically on first render,
|
|
17
|
+
* but you can call it early to control timing or provide a custom
|
|
18
|
+
* WASM URL/bytes.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* // Auto-resolve (works with bundlers)
|
|
22
|
+
* await initWasm();
|
|
23
|
+
*
|
|
24
|
+
* // Explicit URL (CDN, custom path, etc.)
|
|
25
|
+
* await initWasm('/wasm/forme_bg.wasm');
|
|
26
|
+
* await initWasm(new URL('./forme_bg.wasm', import.meta.url));
|
|
27
|
+
*/
|
|
28
|
+
export async function init(module) {
|
|
29
|
+
if (initialized)
|
|
30
|
+
return;
|
|
31
|
+
if (module !== undefined) {
|
|
32
|
+
await initWasm({ module_or_path: module });
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
await initWasm();
|
|
36
|
+
}
|
|
37
|
+
initialized = true;
|
|
38
|
+
}
|
|
39
|
+
// ── Helpers ────────────────────────────────────────────────────────
|
|
40
|
+
function uint8ArrayToBase64(bytes) {
|
|
41
|
+
// Browser-native: binary string → btoa
|
|
42
|
+
let binary = '';
|
|
43
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
44
|
+
binary += String.fromCharCode(bytes[i]);
|
|
45
|
+
}
|
|
46
|
+
return btoa(binary);
|
|
47
|
+
}
|
|
48
|
+
async function resolveFonts(doc) {
|
|
49
|
+
const fonts = doc.fonts;
|
|
50
|
+
if (!fonts?.length)
|
|
51
|
+
return;
|
|
52
|
+
for (const font of fonts) {
|
|
53
|
+
if (font.src instanceof Uint8Array) {
|
|
54
|
+
font.src = uint8ArrayToBase64(font.src);
|
|
55
|
+
}
|
|
56
|
+
else if (typeof font.src === 'string' && !font.src.startsWith('data:')) {
|
|
57
|
+
// In the browser, non-data-URI strings are treated as URLs
|
|
58
|
+
const res = await fetch(font.src);
|
|
59
|
+
if (!res.ok)
|
|
60
|
+
throw new Error(`Failed to fetch font: ${font.src} (${res.status})`);
|
|
61
|
+
const buf = new Uint8Array(await res.arrayBuffer());
|
|
62
|
+
font.src = uint8ArrayToBase64(buf);
|
|
63
|
+
}
|
|
64
|
+
// data URIs pass through as-is (engine extracts base64 portion)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function resolveImages(doc) {
|
|
68
|
+
const children = doc.children;
|
|
69
|
+
if (!children?.length)
|
|
70
|
+
return;
|
|
71
|
+
for (const child of children) {
|
|
72
|
+
await resolveImagesInNode(child);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function resolveImagesInNode(node) {
|
|
76
|
+
const kind = node.kind;
|
|
77
|
+
if (kind?.type === 'Image' && typeof kind.src === 'string') {
|
|
78
|
+
const src = kind.src;
|
|
79
|
+
if (src.startsWith('http://') || src.startsWith('https://')) {
|
|
80
|
+
const res = await fetch(src);
|
|
81
|
+
if (!res.ok)
|
|
82
|
+
throw new Error(`Failed to fetch image: ${src} (${res.status})`);
|
|
83
|
+
const contentType = res.headers.get('content-type') || 'image/png';
|
|
84
|
+
const buf = new Uint8Array(await res.arrayBuffer());
|
|
85
|
+
kind.src = `data:${contentType};base64,${uint8ArrayToBase64(buf)}`;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const children = node.children;
|
|
89
|
+
if (children?.length) {
|
|
90
|
+
for (const child of children) {
|
|
91
|
+
await resolveImagesInNode(child);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// ── Render functions ───────────────────────────────────────────────
|
|
96
|
+
async function ensureInit() {
|
|
97
|
+
if (!initialized)
|
|
98
|
+
await init();
|
|
99
|
+
}
|
|
100
|
+
export async function renderPdf(json) {
|
|
101
|
+
await ensureInit();
|
|
102
|
+
return wasmRenderPdf(json);
|
|
103
|
+
}
|
|
104
|
+
export async function renderPdfWithLayout(json) {
|
|
105
|
+
await ensureInit();
|
|
106
|
+
const result = wasmRenderPdfWithLayout(json);
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
export async function renderDocument(element, options) {
|
|
110
|
+
const { serialize } = await import('@formepdf/react');
|
|
111
|
+
const doc = serialize(element);
|
|
112
|
+
if (options?.embedData !== undefined) {
|
|
113
|
+
doc.embeddedData = JSON.stringify(options.embedData);
|
|
114
|
+
}
|
|
115
|
+
await Promise.all([resolveFonts(doc), resolveImages(doc)]);
|
|
116
|
+
return renderPdf(JSON.stringify(doc));
|
|
117
|
+
}
|
|
118
|
+
export async function renderDocumentWithLayout(element, options) {
|
|
119
|
+
const { serialize } = await import('@formepdf/react');
|
|
120
|
+
const doc = serialize(element);
|
|
121
|
+
if (options?.embedData !== undefined) {
|
|
122
|
+
doc.embeddedData = JSON.stringify(options.embedData);
|
|
123
|
+
}
|
|
124
|
+
await Promise.all([resolveFonts(doc), resolveImages(doc)]);
|
|
125
|
+
return renderPdfWithLayout(JSON.stringify(doc));
|
|
126
|
+
}
|
|
127
|
+
// ── Template rendering ──────────────────────────────────────────────
|
|
128
|
+
export async function renderTemplate(templateJson, dataJson) {
|
|
129
|
+
await ensureInit();
|
|
130
|
+
return wasmRenderTemplatePdf(templateJson, dataJson);
|
|
131
|
+
}
|
|
132
|
+
export async function renderTemplateWithLayout(templateJson, dataJson) {
|
|
133
|
+
await ensureInit();
|
|
134
|
+
const result = wasmRenderTemplatePdfWithLayout(templateJson, dataJson);
|
|
135
|
+
return result;
|
|
136
|
+
}
|
|
137
|
+
// ── Data extraction (browser-native decompression) ──────────────────
|
|
138
|
+
/**
|
|
139
|
+
* Extract embedded JSON data from a Forme-generated PDF.
|
|
140
|
+
* Uses the browser-native DecompressionStream API (no node:zlib).
|
|
141
|
+
*/
|
|
142
|
+
export async function extractData(pdfBytes) {
|
|
143
|
+
const text = new TextDecoder('latin1').decode(pdfBytes);
|
|
144
|
+
// Find the FileSpec referencing forme-data.json
|
|
145
|
+
const fsMatch = text.match(/\/F\s*\(forme-data\.json\)/);
|
|
146
|
+
if (!fsMatch)
|
|
147
|
+
return null;
|
|
148
|
+
// Extract the EmbeddedFile stream object number from /EF << /F N 0 R >>
|
|
149
|
+
const fsStart = fsMatch.index;
|
|
150
|
+
const fsRegion = text.slice(Math.max(0, fsStart - 200), fsStart + 200);
|
|
151
|
+
const efMatch = fsRegion.match(/\/EF\s*<<\s*\/F\s+(\d+)\s+0\s+R\s*>>/);
|
|
152
|
+
if (!efMatch)
|
|
153
|
+
return null;
|
|
154
|
+
const streamObjId = efMatch[1];
|
|
155
|
+
// Find the stream object
|
|
156
|
+
const objPattern = new RegExp(streamObjId + '\\s+0\\s+obj\\b');
|
|
157
|
+
const objMatch = text.match(objPattern);
|
|
158
|
+
if (!objMatch)
|
|
159
|
+
return null;
|
|
160
|
+
const objStart = objMatch.index;
|
|
161
|
+
// Find stream start
|
|
162
|
+
const streamKeyword = text.indexOf('stream', objStart);
|
|
163
|
+
if (streamKeyword === -1)
|
|
164
|
+
return null;
|
|
165
|
+
let streamDataStart = streamKeyword + 6;
|
|
166
|
+
if (pdfBytes[streamDataStart] === 0x0d)
|
|
167
|
+
streamDataStart++;
|
|
168
|
+
if (pdfBytes[streamDataStart] === 0x0a)
|
|
169
|
+
streamDataStart++;
|
|
170
|
+
const endstreamPos = text.indexOf('\nendstream', streamDataStart);
|
|
171
|
+
if (endstreamPos === -1)
|
|
172
|
+
return null;
|
|
173
|
+
const compressedBytes = pdfBytes.slice(streamDataStart, endstreamPos);
|
|
174
|
+
const objRegion = text.slice(objStart, streamKeyword);
|
|
175
|
+
const isCompressed = objRegion.includes('/FlateDecode');
|
|
176
|
+
let jsonBytes;
|
|
177
|
+
if (isCompressed) {
|
|
178
|
+
const ds = new DecompressionStream('deflate');
|
|
179
|
+
const writer = ds.writable.getWriter();
|
|
180
|
+
writer.write(compressedBytes);
|
|
181
|
+
writer.close();
|
|
182
|
+
const reader = ds.readable.getReader();
|
|
183
|
+
const chunks = [];
|
|
184
|
+
while (true) {
|
|
185
|
+
const { done, value } = await reader.read();
|
|
186
|
+
if (done)
|
|
187
|
+
break;
|
|
188
|
+
chunks.push(value);
|
|
189
|
+
}
|
|
190
|
+
const totalLength = chunks.reduce((sum, c) => sum + c.length, 0);
|
|
191
|
+
jsonBytes = new Uint8Array(totalLength);
|
|
192
|
+
let offset = 0;
|
|
193
|
+
for (const chunk of chunks) {
|
|
194
|
+
jsonBytes.set(chunk, offset);
|
|
195
|
+
offset += chunk.length;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
jsonBytes = compressedBytes;
|
|
200
|
+
}
|
|
201
|
+
const jsonString = new TextDecoder('utf-8').decode(jsonBytes);
|
|
202
|
+
return JSON.parse(jsonString);
|
|
203
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@formepdf/core",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.8",
|
|
4
4
|
"description": "WASM-powered PDF rendering engine for Forme",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -10,6 +10,10 @@
|
|
|
10
10
|
"types": "./dist/index.d.ts",
|
|
11
11
|
"import": "./dist/index.js"
|
|
12
12
|
},
|
|
13
|
+
"./browser": {
|
|
14
|
+
"types": "./dist/browser.d.ts",
|
|
15
|
+
"import": "./dist/browser.js"
|
|
16
|
+
},
|
|
13
17
|
"./pkg/forme.js": {
|
|
14
18
|
"types": "./pkg/forme.d.ts",
|
|
15
19
|
"import": "./pkg/forme.js"
|
|
@@ -23,7 +27,7 @@
|
|
|
23
27
|
"test": "vitest run"
|
|
24
28
|
},
|
|
25
29
|
"dependencies": {
|
|
26
|
-
"@formepdf/react": "0.7.
|
|
30
|
+
"@formepdf/react": "0.7.8"
|
|
27
31
|
},
|
|
28
32
|
"peerDependencies": {
|
|
29
33
|
"react": "^18 || ^19"
|