@polotno/pdf-export
v0.4.0
Published
Convert Polotno JSON into vector PDF
Downloads
3,981
Readme
Polotno to Vector PDF
Convert Polotno JSON into a vector PDF, in Node.js or directly in the browser. Optional PDF/X-1a print-ready export (Node only).
npm install @polotno/pdf-exportNode usage
import fs from 'node:fs';
import { jsonToPDF } from '@polotno/pdf-export';
const json = JSON.parse(fs.readFileSync('./polotno.json', 'utf8'));
await jsonToPDF(json, './output.pdf');jsonToPDFBytes(json, attrs) is also exported on the Node entry — useful when you want raw bytes (to upload, attach, etc.) without writing to disk.
Browser usage
import { jsonToPDFBlob } from '@polotno/pdf-export/browser';
async function exportToPDF(store) {
const blob = await jsonToPDFBlob(store.toJSON());
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'design.pdf';
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}Also exported: jsonToPDFBytes(json, attrs): Promise<Uint8Array> — for cases where you want raw bytes (to push to IndexedDB, send via WebTransport, share via navigator.share, etc.).
The browser entry does not support attrs.pdfx1a / attrs.validate — those rely on Ghostscript, which has no browser-side equivalent. Pass them and you'll get a clear runtime error pointing at the Node entry.
CORS
When polotno designs reference remote images, fonts, or SVG sources, the browser fetches those assets at export time. They must be reachable with CORS:
- Google Fonts (
fonts.googleapis.comandfonts.gstatic.com) work out of the box. - Custom asset URLs must be served with
Access-Control-Allow-Origin: *(or your origin), or pre-fetched and passed asdata:URLs in the JSON.
Fonts
Custom fonts registered in the design JSON and Google Fonts are embedded into the PDF automatically as subsetted font files — text stays selectable and renders identically on any machine. System fonts (Arial, Times New Roman, Courier, …) map to the standard PDF base-14 fonts instead, which viewers supply themselves, so they are not embedded in a plain vector export. PDF/X-1a conversion (below) embeds all fonts, including substitutes for the base-14 ones, as the spec requires — text is never converted to outlines.
PDF/X-1a print-ready export (Node only)
Text taller than its box shrinks to fit by default (textOverflow:
'change-font-size', the same default polotno-node exports use). Pass
textOverflow: 'resize' to keep the authored font size — PDF never clips
text, so the content renders at its natural height. ('ellipsis' has no PDF
equivalent; unsupported values fall back to the default.)
For professional printing:
await jsonToPDF(json, './print-ready.pdf', { pdfx1a: true });
// With custom metadata and validation
await jsonToPDF(json, './book-cover.pdf', {
pdfx1a: true,
validate: true,
metadata: {
title: 'My Book Cover',
author: 'Author Name',
application: 'KDP CoverCreator v1.0',
},
});Requires Ghostscript:
- macOS:
brew install ghostscript - Ubuntu:
apt-get install ghostscript - Windows: download from ghostscript.com
Spot color / foil support
For professional printing with special inks like metallic foils or Pantone colors:
await jsonToPDF(json, './output.pdf', {
pdfx1a: true,
spotColors: {
'rgba(255,215,0,1)': {
name: 'Gold Foil',
pantoneCode: 'Pantone 871 C', // optional reference
cmyk: [0, 0.15, 0.5, 0], // CMYK fallback (0–1 range)
overprint: true, // recommended for foils — see below
},
'#C0C0C0': {
name: 'Silver Foil',
cmyk: [0, 0, 0, 0.25],
overprint: true,
},
},
});Any element with a matching fill or stroke color is automatically converted. Color matching is flexible — '#FFD700', '#ffd700', 'rgb(255,215,0)', and 'rgba(255,215,0,1)' all match. CMYK fallback values are used by viewers that don't support spot colors.
Supported on text, lines, figures, and SVG elements.
Overprint
overprint: true emits the PDF graphics state /OP true /op true /OPM 1 whenever the spot color is painted, telling the press to add the spot ink on top of any underlying CMYK rather than knocking it out:
- Without overprint (default): the spot region knocks out CMYK underneath. A misaligned foil die produces a visible white halo at the edge.
- With overprint: CMYK prints continuously through the spot region; the foil is stamped over it. No halo, underlying artwork stays intact.
Acrobat's Output Preview → Simulate Overprinting shows how the press will composite the layers. Verify spot colors in Tools → Print Production → Output Preview → Separations.
For foil regions, prefer plain shapes or simple SVG paths — SVGs that internally use <clipPath> or <mask> may have their spot color flattened to CMYK during PDF/X-1a conversion.
Bleed and crop marks
For print production you usually want extra paper around the trim edge so that ink covers the cut line, plus crop marks for the print shop:
await jsonToPDF(json, './print-ready.pdf', {
pdfx1a: true,
includeBleed: true, // expand each page by its per-side `computedBleed` (defaults to `page.bleed` on every side)
cropMarkSize: 18, // reserve 18 px around the bleed for crop marks
});Set bleed in pixels on each page in the JSON:
{ width: 1080, height: 1080, pages: [{ background: '...', bleed: 36, children: [...] }] }bleed is the all-sides base value. You can also override individual edges with the optional
bleedTop, bleedRight, bleedBottom, and bleedLeft fields:
{ pages: [{ bleed: 36, bleedTop: 72, bleedRight: 0, children: [...] }] }Each side falls back to bleed when its override is absent; an explicit 0 disables bleed on that
edge. Setting bleed never mutates the per-side overrides. The resolved per-side values are exposed
read-only as page.computedBleed → { top, right, bottom, left }. When no overrides are set, every
side equals bleed and output is identical to before. includeBleed honors these per-side values,
and the pdf-import round-trip preserves them.
Element coordinates stay relative to the trim corner — (0, 0) still lands at the top-left of the trim. Backgrounds automatically extend into the bleed strip.
The output PDF gets correct PDF/X page boxes (MediaBox ⊇ BleedBox ⊇ TrimBox = ArtBox) so RIPs and proofers can identify the live area without guessing.
Works on both Node and browser entries — no Ghostscript required if you skip pdfx1a.
DPI handling
The library converts pixel coordinates to PDF points using the dpi value from your JSON (default 72):
const json = { width: 1920, height: 1080, dpi: 300, /* ... */ };
// Uses JSON dpi automatically
await jsonToPDF(json, './output.pdf');
// Or override
await jsonToPDF(json, './output.pdf', { dpi: 150 });A 1920×1080 canvas at 300 DPI is 6.4″ × 3.6″ in the PDF; at 72 DPI it's 26.67″ × 15″.
Development
npm install # postinstall applies patches/ to node_modules
npm run build # builds the Node and browser bundles
npm test # Node-side fixture tests
npm run test:browser # real-Chromium smoke suite (Vitest browser mode)
npm run dev # demo Polotno editor for manual export testing