turbo-html2pdf 0.2.15 → 0.3.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.
- package/Cargo.toml +0 -1
- package/README.md +1 -1
- package/index.d.ts +10 -36
- package/index.js +6 -4
- package/package.json +1 -1
- package/src/errors.rs +1 -14
- package/src/lib.rs +70 -94
- package/turbo-pdf-napi.darwin-arm64.node +0 -0
- package/turbo-pdf-napi.linux-arm64-gnu.node +0 -0
- package/turbo-pdf-napi.linux-x64-gnu.node +0 -0
- package/turbo-pdf-napi.linux-x64-musl.node +0 -0
- package/turbo-pdf-napi.win32-x64-msvc.node +0 -0
package/Cargo.toml
CHANGED
package/README.md
CHANGED
|
@@ -201,7 +201,7 @@ fs.writeFileSync('out.pdf', pdf) // %PDF-1.7
|
|
|
201
201
|
|
|
202
202
|
## Status
|
|
203
203
|
|
|
204
|
-
`v0.
|
|
204
|
+
`v0.3.1`. The core engine is complete and heavily tested (the `turbo-html2pdf-core`
|
|
205
205
|
crate holds 100% line coverage with a cyclomatic-complexity ≤ 5 gate). Bindings:
|
|
206
206
|
Node (napi) and WebAssembly. See [`docs/`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/docs/) for the full guide and
|
|
207
207
|
[`benches/competitive/`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/benches/competitive/) for the benchmark harness.
|
package/index.d.ts
CHANGED
|
@@ -88,39 +88,6 @@ export interface Watermark {
|
|
|
88
88
|
tiled?: boolean;
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
/** A text-only watermark for {@link stamp}. Unlike {@link Watermark} (the
|
|
92
|
-
* render-time mark, which may be text or image), the post-emit overlay is
|
|
93
|
-
* text-only. Its text is shaped and embedded with a real, subsetted font —
|
|
94
|
-
* the bundled sans-serif by default, or {@link StampWatermark.font} when you
|
|
95
|
-
* supply one — so the output is self-contained and never depends on a base-14
|
|
96
|
-
* font the reader may or may not have installed. */
|
|
97
|
-
export interface StampWatermark {
|
|
98
|
-
/** The word to stamp. */
|
|
99
|
-
text: string;
|
|
100
|
-
/** Fill color `#rrggbb`. Defaults to gray. */
|
|
101
|
-
color?: string;
|
|
102
|
-
/** Fill opacity `0.0..=1.0`. Defaults to `0.15`. */
|
|
103
|
-
opacity?: number;
|
|
104
|
-
/** Rotation in degrees. Defaults to `45`. */
|
|
105
|
-
angle?: number;
|
|
106
|
-
/** Font size in CSS px. Defaults to `64`. */
|
|
107
|
-
fontSize?: number;
|
|
108
|
-
/** Font (TrueType/OTF bytes) to shape and embed the stamp text with. Omit
|
|
109
|
-
* for the bundled sans-serif. */
|
|
110
|
-
font?: Buffer;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/** Options for {@link stamp}: the watermark plus the optional decrypt/
|
|
114
|
-
* re-encrypt round trip. */
|
|
115
|
-
export interface StampOptions {
|
|
116
|
-
/** The watermark overlaid on every page. */
|
|
117
|
-
watermark: StampWatermark;
|
|
118
|
-
/** Opens an encrypted `pdf` input. Omit for a plaintext input. */
|
|
119
|
-
password?: string;
|
|
120
|
-
/** Re-encrypts the stamped output. Omit for plaintext output. */
|
|
121
|
-
encryption?: Encryption;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
91
|
/** Compile-time knobs: partials, missing-value policy, and include depth. */
|
|
125
92
|
export interface CompileOptions {
|
|
126
93
|
/** Partial templates by name, for `{% include %}`. */
|
|
@@ -237,6 +204,13 @@ export function render(templateHtml: string, opts?: RenderOptions, fonts?: Fonts
|
|
|
237
204
|
* already-emitted bytes. Throws `TurboPdfError` if any input fails to parse. */
|
|
238
205
|
export function appendPdf(base: Buffer, extras: Buffer[]): Buffer;
|
|
239
206
|
|
|
240
|
-
/**
|
|
241
|
-
*
|
|
242
|
-
|
|
207
|
+
/** Debug/conformance seam (NOT part of the render path): lay `html` out (its
|
|
208
|
+
* own `<style>` blocks plus `css`) at `width`×`height` px with the bundled
|
|
209
|
+
* default fonts, and return a JSON string — an array of
|
|
210
|
+
* `{ cid, x, y, width, height }`, one per box whose source element carried a
|
|
211
|
+
* `data-cid="..."` attribute, in document order. Coordinates are absolute px
|
|
212
|
+
* (page origin top-left) and sizes are the border box, matching a browser's
|
|
213
|
+
* `getBoundingClientRect()`. Only box-generating elements (block, inline-block,
|
|
214
|
+
* flex/grid/table items, replaced `<img>`) resolve a `data-cid`; a
|
|
215
|
+
* `display:inline` element is flattened during box generation and drops it. */
|
|
216
|
+
export function layoutBoxes(html: string, css: string, width: number, height: number): string;
|
package/index.js
CHANGED
|
@@ -133,9 +133,11 @@ const render = guard((templateHtml, opts, fonts) => native.render(templateHtml,
|
|
|
133
133
|
// Glue foreign PDFs after `base`; parse faults surface as a typed TurboPdfError.
|
|
134
134
|
const appendPdf = guard((base, extras) => native.appendPdf(base, extras));
|
|
135
135
|
|
|
136
|
-
//
|
|
137
|
-
//
|
|
138
|
-
const
|
|
136
|
+
// Debug/conformance seam: lay HTML out and return the placed geometry of every
|
|
137
|
+
// `data-cid`-tagged box as a JSON string. Not part of the render path.
|
|
138
|
+
const layoutBoxes = guard((html, css, width, height) =>
|
|
139
|
+
native.layoutBoxes(html, css, width, height),
|
|
140
|
+
);
|
|
139
141
|
|
|
140
|
-
module.exports = { compile, render, appendPdf,
|
|
142
|
+
module.exports = { compile, render, appendPdf, layoutBoxes, Fonts: native.Fonts, TurboPdfError };
|
|
141
143
|
module.exports.default = module.exports;
|
package/package.json
CHANGED
package/src/errors.rs
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
//! JS wrapper (`index.js`) detects the prefix and rethrows a typed
|
|
8
8
|
//! `TurboPdfError` whose `.code` and `.span` mirror this payload.
|
|
9
9
|
|
|
10
|
-
use turbo_html2pdf_core::{AppendError, CompileError, ErrorCode, RenderError, Span
|
|
10
|
+
use turbo_html2pdf_core::{AppendError, CompileError, ErrorCode, RenderError, Span};
|
|
11
11
|
|
|
12
12
|
/// Sentinel that marks a `reason` string as a structured turbo-pdf error. The JS
|
|
13
13
|
/// wrapper splits on this to recover the JSON payload.
|
|
@@ -55,16 +55,3 @@ pub fn from_render(e: RenderError) -> napi::Error {
|
|
|
55
55
|
pub fn from_append(e: AppendError) -> napi::Error {
|
|
56
56
|
encode(ErrorCode::Render, &e.to_string(), Span::default())
|
|
57
57
|
}
|
|
58
|
-
|
|
59
|
-
/// Map a PDF stamp failure to a typed N-API error. Stamp errors carry no source
|
|
60
|
-
/// span, so a zeroed span is used under the generic `Render` code.
|
|
61
|
-
pub fn from_stamp(e: StampError) -> napi::Error {
|
|
62
|
-
encode(ErrorCode::Render, &e.to_string(), Span::default())
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/// Map a caller-supplied stamp watermark font that failed to parse to a typed
|
|
66
|
-
/// N-API error. Mirrors [`from_stamp`]'s shape (generic `Render` code, zeroed
|
|
67
|
-
/// span) since font parsing carries no source span either.
|
|
68
|
-
pub fn from_invalid_font(message: &str) -> napi::Error {
|
|
69
|
-
encode(ErrorCode::Render, message, Span::default())
|
|
70
|
-
}
|
package/src/lib.rs
CHANGED
|
@@ -33,10 +33,10 @@ use std::collections::HashMap;
|
|
|
33
33
|
|
|
34
34
|
use turbo_html2pdf_core::style::TokenSet;
|
|
35
35
|
use turbo_html2pdf_core::{
|
|
36
|
-
append_pdfs, build_cascade, compile as core_compile, emit_pdf_with_images,
|
|
37
|
-
|
|
38
|
-
Encryption,
|
|
39
|
-
|
|
36
|
+
append_pdfs, build_cascade, compile as core_compile, emit_pdf_with_images, layout_boxes,
|
|
37
|
+
render_pages, style::parse_stylesheet, CidBox, CompileOptions, Diagnostics, EmitOptions,
|
|
38
|
+
Encryption, FontRegistry, ImageWatermark, MissingPolicy, NoImages, Permissions, RenderInputs,
|
|
39
|
+
Rgba, TextWatermark, Watermark,
|
|
40
40
|
};
|
|
41
41
|
|
|
42
42
|
use convert::{build_registry, diagnostics_to_js, JsDiagnostic, JsFont, JsImage, MapResolver};
|
|
@@ -299,6 +299,72 @@ pub fn render_oneshot(
|
|
|
299
299
|
run_pipeline(&program, opts.unwrap_or_default(), fonts)
|
|
300
300
|
}
|
|
301
301
|
|
|
302
|
+
/// Lay `html` out (author `<style>` blocks + `css`) at `width`×`height` px with
|
|
303
|
+
/// the bundled default fonts, and return — as a JSON string — the placed
|
|
304
|
+
/// geometry of every box whose source element carries a `data-cid="..."`
|
|
305
|
+
/// attribute: `[{ "cid", "x", "y", "width", "height" }, …]`, in document order.
|
|
306
|
+
///
|
|
307
|
+
/// A debug/conformance seam (drives `benches/conformance` against Chromium's
|
|
308
|
+
/// `getBoundingClientRect()`); it does NOT touch the compile→render→emit path.
|
|
309
|
+
/// Coordinates are absolute px (page origin at top-left) and sizes are the border
|
|
310
|
+
/// box, matching a browser's client rect. See the core `layout_boxes` for the
|
|
311
|
+
/// inline-flattening limitation (tag box-generating elements).
|
|
312
|
+
#[napi(js_name = "layoutBoxes")]
|
|
313
|
+
pub fn layout_boxes_json(
|
|
314
|
+
html: String,
|
|
315
|
+
css: String,
|
|
316
|
+
width: f64,
|
|
317
|
+
height: f64,
|
|
318
|
+
) -> napi::Result<String> {
|
|
319
|
+
let fonts = FontRegistry::new();
|
|
320
|
+
let mut diags = Diagnostics::default();
|
|
321
|
+
let boxes = layout_boxes(&html, &css, width as f32, height as f32, &fonts, &mut diags)
|
|
322
|
+
.map_err(errors::from_render)?;
|
|
323
|
+
Ok(cid_boxes_to_json(&boxes))
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/// Serialize the placed boxes to a JSON array by hand — a handful of numeric
|
|
327
|
+
/// fields, so a manual encoder keeps the dependency-free thin-bridge contract
|
|
328
|
+
/// without pulling `serde` onto the core `CidBox` type.
|
|
329
|
+
fn cid_boxes_to_json(boxes: &[CidBox]) -> String {
|
|
330
|
+
let mut s = String::from("[");
|
|
331
|
+
for (i, b) in boxes.iter().enumerate() {
|
|
332
|
+
if i > 0 {
|
|
333
|
+
s.push(',');
|
|
334
|
+
}
|
|
335
|
+
s.push_str(&format!(
|
|
336
|
+
"{{\"cid\":{},\"x\":{},\"y\":{},\"width\":{},\"height\":{}}}",
|
|
337
|
+
json_string(&b.cid),
|
|
338
|
+
b.x,
|
|
339
|
+
b.y,
|
|
340
|
+
b.width,
|
|
341
|
+
b.height
|
|
342
|
+
));
|
|
343
|
+
}
|
|
344
|
+
s.push(']');
|
|
345
|
+
s
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/// Encode `s` as a JSON string literal (quotes + the mandatory escapes), so a
|
|
349
|
+
/// `data-cid` containing a quote/backslash/control char can't break the array.
|
|
350
|
+
fn json_string(s: &str) -> String {
|
|
351
|
+
let mut out = String::with_capacity(s.len() + 2);
|
|
352
|
+
out.push('"');
|
|
353
|
+
for c in s.chars() {
|
|
354
|
+
match c {
|
|
355
|
+
'"' => out.push_str("\\\""),
|
|
356
|
+
'\\' => out.push_str("\\\\"),
|
|
357
|
+
'\n' => out.push_str("\\n"),
|
|
358
|
+
'\r' => out.push_str("\\r"),
|
|
359
|
+
'\t' => out.push_str("\\t"),
|
|
360
|
+
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
|
361
|
+
c => out.push(c),
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
out.push('"');
|
|
365
|
+
out
|
|
366
|
+
}
|
|
367
|
+
|
|
302
368
|
/// Glue one or more foreign PDF documents after `base`, page by page, returning
|
|
303
369
|
/// the merged PDF. Equivalent to `RenderOptions.appendPdfs` but usable on
|
|
304
370
|
/// already-emitted bytes. Throws `TurboPdfError` if any input fails to parse or
|
|
@@ -310,96 +376,6 @@ pub fn append_pdf(base: Buffer, extras: Vec<Buffer>) -> napi::Result<Buffer> {
|
|
|
310
376
|
Ok(merged.into())
|
|
311
377
|
}
|
|
312
378
|
|
|
313
|
-
/// A text-only watermark for [`stamp`]. Unlike [`JsWatermark`] (the render-time
|
|
314
|
-
/// mark, which may be text or image), the post-emit overlay only ever draws
|
|
315
|
-
/// shaped, embedded text — there is no `image`/`tiled` shape here. The shown
|
|
316
|
-
/// text is embedded via a real, subsetted font: `font` when supplied, else the
|
|
317
|
-
/// bundled sans-serif (the same resolution the render-time watermark uses).
|
|
318
|
-
#[napi(object)]
|
|
319
|
-
pub struct JsStampWatermark {
|
|
320
|
-
/// The word to stamp.
|
|
321
|
-
pub text: String,
|
|
322
|
-
/// Fill color `#rrggbb`. Defaults to gray.
|
|
323
|
-
pub color: Option<String>,
|
|
324
|
-
/// Fill opacity `0.0..=1.0`. Defaults to `0.15`.
|
|
325
|
-
pub opacity: Option<f64>,
|
|
326
|
-
/// Rotation in degrees. Defaults to `45`.
|
|
327
|
-
pub angle: Option<f64>,
|
|
328
|
-
/// Font size in CSS px. Defaults to `64`.
|
|
329
|
-
pub font_size: Option<f64>,
|
|
330
|
-
/// Optional font (TrueType/OTF bytes) to shape + embed the watermark text
|
|
331
|
-
/// with; omit for the bundled sans-serif.
|
|
332
|
-
pub font: Option<Buffer>,
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
/// Options for [`stamp`]: the watermark plus the optional decrypt/re-encrypt
|
|
336
|
-
/// round trip.
|
|
337
|
-
#[napi(object)]
|
|
338
|
-
pub struct JsStampOptions {
|
|
339
|
-
/// The watermark overlaid on every page.
|
|
340
|
-
pub watermark: JsStampWatermark,
|
|
341
|
-
/// Opens an encrypted `pdf` input. Omit for a plaintext input.
|
|
342
|
-
pub password: Option<String>,
|
|
343
|
-
/// Re-encrypts the stamped output. Omit for plaintext output.
|
|
344
|
-
pub encryption: Option<JsEncryption>,
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
/// Overlay a watermark on EVERY page of an existing PDF, optionally decrypting
|
|
348
|
-
/// the input and re-encrypting the output. Throws `TurboPdfError` on failure.
|
|
349
|
-
#[napi]
|
|
350
|
-
pub fn stamp(pdf: Buffer, opts: JsStampOptions) -> napi::Result<Buffer> {
|
|
351
|
-
let watermark = build_stamp_watermark(opts.watermark)?;
|
|
352
|
-
let password = opts.password;
|
|
353
|
-
let encryption = opts.encryption.map(JsEncryption::into_core);
|
|
354
|
-
let stamped = core_stamp(
|
|
355
|
-
pdf.as_ref(),
|
|
356
|
-
&watermark,
|
|
357
|
-
password.as_deref(),
|
|
358
|
-
encryption.as_ref(),
|
|
359
|
-
)
|
|
360
|
-
.map_err(errors::from_stamp)?;
|
|
361
|
-
Ok(stamped.into())
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
/// Lower a [`JsStampWatermark`] into the core [`StampWatermark`], applying the
|
|
365
|
-
/// documented defaults (gray / 0.15 / 45° / 64px) for every omitted field.
|
|
366
|
-
/// Throws a typed `TurboPdfError` if `font` is supplied but is not a valid
|
|
367
|
-
/// TrueType/OTF font.
|
|
368
|
-
fn build_stamp_watermark(w: JsStampWatermark) -> napi::Result<StampWatermark> {
|
|
369
|
-
let face = resolve_stamp_face(w.font)?;
|
|
370
|
-
Ok(StampWatermark {
|
|
371
|
-
text: w.text,
|
|
372
|
-
font_size: w.font_size.map(|v| v as f32).unwrap_or(64.0),
|
|
373
|
-
color: w
|
|
374
|
-
.color
|
|
375
|
-
.as_deref()
|
|
376
|
-
.and_then(parse_hex_color)
|
|
377
|
-
.unwrap_or(Rgba::new(128, 128, 128, 255)),
|
|
378
|
-
opacity: w.opacity.map(|v| v as f32).unwrap_or(0.15),
|
|
379
|
-
angle_deg: w.angle.map(|v| v as f32).unwrap_or(45.0),
|
|
380
|
-
face,
|
|
381
|
-
})
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
/// Resolve the [`FontFace`] the stamp overlay shapes/embeds its text with:
|
|
385
|
-
/// the caller's `font` bytes when supplied (parsed the SAME way the render
|
|
386
|
-
/// path parses caller fonts, see [`convert::build_registry`]), else the
|
|
387
|
-
/// bundled sans-serif — the same resolution [`build_watermark`] uses for the
|
|
388
|
-
/// render-time mark (`FontRegistry::new().select(&[], 400, false)`).
|
|
389
|
-
fn resolve_stamp_face(font: Option<Buffer>) -> napi::Result<FontFace> {
|
|
390
|
-
match font {
|
|
391
|
-
Some(bytes) => {
|
|
392
|
-
FontFace::from_bytes(bytes.to_vec(), "watermark", 400, false).ok_or_else(|| {
|
|
393
|
-
errors::from_invalid_font("stamp watermark font: not a valid TrueType/OTF font")
|
|
394
|
-
})
|
|
395
|
-
}
|
|
396
|
-
None => Ok(FontRegistry::new()
|
|
397
|
-
.select(&[], 400, false)
|
|
398
|
-
.expect("bundled sans face")
|
|
399
|
-
.clone()),
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
|
|
403
379
|
/// The shared render pipeline: cascade + geometry + fonts -> `render_pages` ->
|
|
404
380
|
/// `emit_pdf`. Diagnostics flow into the result; only fatal faults throw.
|
|
405
381
|
fn run_pipeline(
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|