VibeFox JS PDF — Help
Overview
VibeFox JS PDF creates, opens, changes, shows and checks PDF files in the browser and in Node. It writes real PDF files from scratch (text, your own fonts, images, SVG as vectors, tables, HTML, forms) and opens existing ones to change them; its viewer shows any PDF file with its own renderer, with search, thumbnails, annotations, form filling, page editing and redaction. Digital signatures, encryption, PDF/A and PDF/UA, document comparison and a WYSIWYG template designer are part of the same file. It is plain JavaScript with no dependencies and works with or without a framework.
A document is an object you build with methods, new PdfDocument(options), and save with toBytes() or save(); no DOM is needed for that. The components — the viewer createPdfViewer(target, options), the designer createPdfDesigner and the comparison view createPdfCompare — are controlled through the same methods as every VibeFox JS library: setOptions, on, getState, setState, setTheme, destroy.
Key features
- Documents: pages of any size, flowing text with automatic page breaks, absolute positioning, shapes and paths, JPEG and PNG (with transparency), SVG drawn as vectors, tables with repeated headers, headers and footers with page numbers, watermarks, bookmarks, links, metadata, JSON snapshots.
- Fonts: the 14 standard PDF fonts (Latin and Cyrillic) and your own .ttf, .otf and .woff files, embedded as subsets with kerning, a fallback chain and full Unicode.
- HTML to PDF with a CSS cascade, tables, lists, images, links, bookmarks from headings and form controls as PDF fields.
- Charts, grids, diagrams, Gantt charts and documents of the other VibeFox JS libraries as vector graphics in one line.
- Existing files: open (also damaged and encrypted files), draw on pages, insert, remove, move, rotate, copy, extract, split and merge pages; incremental saving keeps the original bytes.
- Viewer: any PDF file drawn by the library's own renderer (no other library needed), continuous scrolling of thousands of pages, zoom, rotation, thumbnails, bookmarks, layers, a selectable text layer and search, page editing with drag and drop, ready-made styles.
- Annotations (highlight, underline, ink, shapes, notes with replies, text boxes, stamps) saved as real PDF annotations, visual signatures, flattening, JSON and XFDF exchange.
- Forms: text fields, check boxes, radio buttons, lists, signature fields and buttons; filling forms of any file, validation, FDF / XFDF / JSON data, filling in the viewer.
- Redaction that removes the content (text, vector graphics, image pixels), search and extraction of text, comparison of two documents with a side-by-side view.
- Digital signatures (PAdES, PKCS#7) with WebCrypto keys or .p12 files, time stamps, validation, long-term validation data; AES encryption and permissions; PDF/A-2 / -3, PDF/UA-1 and tagged PDF with checks and conversion.
- Templates with data placeholders, tables over pages and barcodes (QR, Data Matrix, Code 128, EAN …), rendered in the browser or in Node, and a visual designer for them.
Requirements
- A current web browser for the components (viewer, designer, comparison view).
- No runtime dependencies. The library makes no network requests of its own: a URL you pass (a PDF file, an image, a font) is loaded with
fetchonly then, time stamp and revocation requests go through your own callbacks. - Node.js: the ES module can be imported in Node (no DOM is touched at import). Creating documents,
loadPdf, HTML strings to PDF, templates, text extraction, redaction, comparison of text, PDF/A conversion and checks work there;save()writes a file. Digital signatures, encryption with AES-256 and opening AES-256 files needcrypto.subtle(Node 19 and newer; in browsers a secure page:httpsorlocalhost). - Optional: pdf.js. The library draws PDF files with its own renderer; if you prefer pdf.js for the original content of loaded files, connect your own copy of it (see Rendering PDF files). It is never included in the library files.
Installation
Files of the library
VibeFox JS PDF is a separate product with its own files. The whole JavaScript of the library is one file and the styles are one CSS file: a page needs exactly these two. The other files are optional.
| File | What it is |
|---|---|
vibefox-js-pdf.global.js | The library for a classic <script> tag; defines one global variable, VibeFoxJSPdf. Minified: vibefox-js-pdf.global.min.js. |
vibefox-js-pdf.esm.js | The same code as an ES module. Minified: vibefox-js-pdf.esm.min.js. |
vibefox-js-pdf.css | All styles of the library, inside @layer vfjs; includes the themes light, dark and high-contrast. Minified: vibefox-js-pdf.min.css. |
vibefox-js-themes.css | Optional theme pack: 18 ready-made themes (see Theming and styling). Minified: vibefox-js-themes.min.css. |
locales/vibefox-js-pdf.<lang>.js | Optional language files, one for each language except English (see Localization and RTL). The same language as an ES module: .esm.js; as plain strings: .json. |
vibefox-js-pdf.d.ts | TypeScript declarations (also vibefox-js-pdf.esm.d.ts). |
*.js.map | Source maps. |
vibefox-js-pdf-react.js, vibefox-js-pdf-vue.js, vibefox-js-pdf-svelte.js, vibefox-js-pdf-jquery.js | Optional framework wrappers (each with its .d.ts). |
vibefox-js-pdf-angular | Optional Angular package (Angular Package Format). |
vibefox-js-pdf-wc.js | Optional Web Components wrapper (custom elements). |
Script tag
Link the CSS file and the script. The global variable VibeFoxJSPdf holds every export of the library. This also works from a file opened from disk (file://).
<link rel="stylesheet" href="vibefox-js-pdf.css">
<script src="vibefox-js-pdf.global.js"></script>
<script>
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: doc });
</script>
ES module
Import the ES module file and link the CSS file. Browsers load modules only over http(s), not from file://.
<link rel="stylesheet" href="vibefox-js-pdf.css">
<script type="module">
import { createPdfViewer } from './vibefox-js-pdf.esm.js';
const viewer = createPdfViewer('#app', { document: doc });
</script>
npm
The library is also prepared as an npm package named @vibefox/js-pdf. Install it from the package folder (or its packed .tgz file) that you received, then import it by name. Bundlers take the CSS through the @vibefox/js-pdf/css export.
npm install ./vibefox-js-pdf
import { createPdfViewer } from '@vibefox/js-pdf';
import '@vibefox/js-pdf/css';
Exports of the package: @vibefox/js-pdf (ES module), @vibefox/js-pdf/min, @vibefox/js-pdf/global, @vibefox/js-pdf/global.min, @vibefox/js-pdf/css, @vibefox/js-pdf/min.css, @vibefox/js-pdf/themes, @vibefox/js-pdf/themes.min.css, @vibefox/js-pdf/locales/<lang>, @vibefox/js-pdf/locales/<lang>.json. TypeScript finds the declarations by itself.
Framework wrappers
The wrappers are small separate files; the library works without them. Each wrapper needs only VibeFox JS PDF and its framework (a peer dependency). The wrappers do not load CSS: link vibefox-js-pdf.css yourself.
| Framework | File | npm package | Supported versions |
|---|---|---|---|
| React | vibefox-js-pdf-react.js | @vibefox/js-pdf-react | React 16.8 and newer |
| Vue 3 | vibefox-js-pdf-vue.js | @vibefox/js-pdf-vue | Vue 3.3 and newer |
| Angular | vibefox-js-pdf-angular | @vibefox/js-pdf-angular | Angular 17 and newer |
| Svelte | vibefox-js-pdf-svelte.js | @vibefox/js-pdf-svelte | Svelte 3, 4 and 5 |
| jQuery | vibefox-js-pdf-jquery.js | @vibefox/js-pdf-jquery | jQuery 1.12 to 4.x |
| Web Components | vibefox-js-pdf-wc.js | @vibefox/js-pdf-wc | no framework |
The ES module wrappers import the library as @vibefox/js-pdf. Without npm, map that name to vibefox-js-pdf.esm.js in your bundler settings or in an import map. The jQuery wrapper takes the library from the global VibeFoxJSPdf.
Common rules of all wrappers: props / inputs are the options of the library (changed ones go to setData or one setOptions call); events are framework events with the same payload object as on(); the instance is available for every method; on the server (SSR) an empty container is rendered and the instance is created in the browser only. The option style (ready-made look) is the prop variant in React, Vue, Svelte and Angular, because style and className / class belong to the host element.
Web Components
Load vibefox-js-pdf-wc.js after the library file. It defines the elements <vfjs-pdf-viewer>, <vfjs-pdf-designer> and <vfjs-pdf-compare> from the global VibeFoxJSPdf. Attributes are options in kebab-case (JSON for objects and arrays), properties are options, the methods of the component are methods of the element, events are CustomEvents named vfjspdfviewer:<event> (designer: vfjspdfdesigner:<event>, comparison: vfjspdfcompare:<event>) with the payload in detail. The element uses the light DOM, so the CSS of the library and your page CSS apply as usual.
<link rel="stylesheet" href="vibefox-js-pdf.css">
<script src="vibefox-js-pdf.global.js"></script>
<script type="module" src="vibefox-js-pdf-wc.js"></script>
<vfjs-pdf-viewer id="v" style="height: 600px" sidebar="thumbnails"></vfjs-pdf-viewer>
<script>
const el = document.getElementById('v');
const doc = new VibeFoxJSPdf.PdfDocument();
doc.text('Hello from a Web Component');
el.document = doc;
el.addEventListener('vfjspdfviewer:pageChange', (e) => console.log(e.detail.page));
</script>
With a bundler: import * as lib from '@vibefox/js-pdf'; import { define } from '@vibefox/js-pdf-wc'; define(lib);
Quick start
Plain HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="vibefox-js-pdf.css">
<script src="vibefox-js-pdf.global.js"></script>
</head>
<body>
<button id="save">Save PDF</button>
<div id="preview" style="height: 600px"></div>
<script>
const doc = new VibeFoxJSPdf.PdfDocument({
format: 'A4',
metadata: { title: 'Sales report' },
footer: '{page} / {pages}',
});
doc.text('Sales report', { size: 22, bold: true });
doc.text('The table lists the orders of the month.', { marginBottom: 12 });
doc.table({
columns: [
{ header: 'Item', field: 'item' },
{ header: 'Price', field: 'price', width: 80, align: 'right', format: (v) => v.toFixed(2) },
],
rows: [{ item: 'Widget', price: 990 }, { item: 'Gadget', price: 1490 }],
zebra: '#f4f6f8',
});
// the viewer shows the document before it is saved and follows every change
const viewer = VibeFoxJSPdf.createPdfViewer('#preview', { document: doc, sidebar: 'thumbnails' });
doc.text('Added later: the preview updates by itself.');
document.getElementById('save').onclick = () => doc.save('report.pdf');
</script>
</body>
</html>
A document needs no element: build it, then save it. The viewer fills its element: give the element a height (without one, the viewer is 400 px high: the variable --vfjs-pdf-min-height).
Open a PDF file
const input = document.createElement('input');
input.type = 'file';
input.accept = 'application/pdf';
input.onchange = async () => {
const pdf = await VibeFoxJSPdf.loadPdf(input.files[0]); // bytes, a Blob / File or a URL
viewer.setDocument(pdf); // drawn by the library itself
};
document.body.append(input);
Node
import { PdfDocument } from '@vibefox/js-pdf';
const doc = new PdfDocument();
doc.text('Hello from Node');
await doc.save('out.pdf'); // Node: writes the file; browser: downloads it
const bytes = await doc.toBytes(); // or the bytes (Uint8Array)
React
import { useMemo, useRef } from 'react';
import { PdfDocument } from '@vibefox/js-pdf';
import { VibeFoxJSPdfViewerReact } from '@vibefox/js-pdf-react';
import '@vibefox/js-pdf/css';
export function Report() {
const viewer = useRef(null); // the VibeFoxJSPdfViewer instance
const doc = useMemo(() => {
const d = new PdfDocument();
d.text('Hello from React', { size: 18 });
return d;
}, []);
return (
<div style={{ height: 600 }}>
<button onClick={() => viewer.current.download()}>Download</button>
<VibeFoxJSPdfViewerReact ref={viewer} document={doc} sidebar="thumbnails" onPageChange={(e) => console.log(e.page)} />
</div>
);
}
The other wrappers of the package are VibeFoxJSPdfDesignerReact and VibeFoxJSPdfCompareReact.
Vue 3
<script setup>
import { shallowRef } from 'vue';
import { PdfDocument } from '@vibefox/js-pdf';
import { VibeFoxJSPdfViewerVue } from '@vibefox/js-pdf-vue';
import '@vibefox/js-pdf/css';
const doc = new PdfDocument();
doc.text('Hello from Vue');
const pdf = shallowRef(doc);
</script>
<template>
<VibeFoxJSPdfViewerVue :document="pdf" style="height: 600px" @page-change="(e) => console.log(e.page)" />
</template>
Pass a document with shallowRef: the viewer works with the document object itself, not with a deep reactive copy.
Angular
import { Component } from '@angular/core';
import { PdfDocument } from '@vibefox/js-pdf';
import { VibeFoxJSPdfViewerComponent } from '@vibefox/js-pdf-angular';
@Component({
selector: 'app-root',
standalone: true,
imports: [VibeFoxJSPdfViewerComponent],
template: `
<vfjs-pdf-viewer-ng #viewer [document]="doc" style="display: block; height: 600px"
(pageChange)="changed($event)"></vfjs-pdf-viewer-ng>
<button (click)="viewer.instance?.download()">Download</button>`,
})
export class AppComponent {
doc = new PdfDocument();
constructor() { this.doc.text('Hello from Angular'); }
changed(e: unknown) { console.log(e); }
}
Link vibefox-js-pdf.css in angular.json (styles) or in index.html. For NgModule applications import VibeFoxJSPdfModule; the other components are vfjs-pdf-designer-ng and vfjs-pdf-compare-ng.
Svelte
<script>
import { PdfDocument } from '@vibefox/js-pdf';
import { vfjsPdfViewer } from '@vibefox/js-pdf-svelte';
const doc = new PdfDocument();
doc.text('Hello from Svelte');
</script>
<div style="height: 600px" use:vfjsPdfViewer={{ document: doc }}
on:vfjspdfviewer:pageChange={(e) => console.log(e.detail.page)}></div>
jQuery
<script src="jquery.min.js"></script>
<link rel="stylesheet" href="vibefox-js-pdf.css">
<script src="vibefox-js-pdf.global.js"></script>
<script src="vibefox-js-pdf-jquery.js"></script>
<script>
const doc = new VibeFoxJSPdf.PdfDocument();
doc.text('Hello from jQuery');
$('#viewer').vfjsPdfViewer({ document: doc })
.on('vfjspdfviewer:pageChange', (e, payload) => console.log(payload.page));
</script>
Core concepts
Documents and pages
PdfDocument is the document model: a list of pages (PdfPage), the bookmarks (outline), metadata and options. It is the same object for a document you build and for a file opened with loadPdf(); every method works on both. It needs no DOM.
- Units are PDF points (pt, 1/72 inch; 1 CSS px = 0.75 pt). Coordinates start at the top-left corner of the page and grow to the right and down. An A4 page is 595.28 × 841.89 pt.
- Pages are counted from 0 in the methods of documents and pages (
doc.page(0),addAnnotation(0, …)) and from 1 in the viewer (goToPage(1)) and in page range strings ('1-3, 5'). - Two ways to place content: the flow (
doc.text(),doc.table(),doc.image(),doc.addHtml()— from a cursor inside the margins, new pages are added when needed) and absolute positioning on a page (page.text(…, { x, y }),page.drawRect(), …). - Colors are
'#rgb','#rrggbb'or[r, g, b](0–255);nullor'none'means no fill / no stroke. - Saving is asynchronous:
await doc.toBytes()returns aUint8Array;save(filename),toDataURL()andtoBlobURL()are built on it.
const report = new VibeFoxJSPdf.PdfDocument({ format: 'A4', orientation: 'portrait', margins: { top: 56, right: 50, bottom: 56, left: 50 } });
report.text('Flowing text starts at the top margin.');
const page = report.currentPage; // the page the flow cursor is on
page.drawRect(50, 120, 200, 60, { fill: '#e0f2fe', stroke: '#0369a1', radius: 6 });
page.text('Placed at x 60, y 140', { x: 60, y: 140, size: 10 });
console.log(report.pageCount, report.cursor); // 1 { page: 0, y: … }
const bytes = await report.toBytes();
Components
The viewer, the designer and the comparison view are VibeFox JS components. Create one with its factory (createPdfViewer, createPdfDesigner, createPdfCompare) or with new on the class (VibeFoxJSPdfViewer, VibeFoxJSPdfDesigner, VibeFoxJSPdfCompare), change it with setOptions, remove it with destroy(). The target is an element or a selector.
const v = VibeFoxJSPdf.createPdfViewer('#app', { document: doc, zoom: 1.25, sidebar: 'outline' });
v.setOptions({ layout: 'single', toolbar: false });
v.goToPage(2);
v.destroy();
The viewer shows a document live: it listens to the change event of the document, so whatever you add or change is shown at once, before the file is saved.
Events
Every event handler receives one payload object. Subscribe in the options (on: { pageChange: fn }) or later with on, once and off; on('*', (event, payload) => …) receives every event. Documents are event emitters too.
viewer.on('pageChange', (e) => console.log(`page ${e.page} of ${e.pages}`));
viewer.on('zoomChange', (e) => console.log(e.zoom));
doc.on('change', (e) => console.log('changed:', e.type));
doc.on('save', (e) => console.log(e.filename, e.size));
Every VibeFox JS component emits ready, optionsChange, themeChange and destroy. The full lists are in API reference.
State snapshots
getState() of the viewer returns { page, zoom, style, rotation, sidebar }; setState(state) restores it (a key that is missing keeps the current value). The designer state is { page, zoom, preview, selection, grid, snap, panel }, the comparison view state { layout, change, zoom }.
localStorage.setItem('pdf-view', JSON.stringify(viewer.getState()));
viewer.setState(JSON.parse(localStorage.getItem('pdf-view')));
A whole document is saved as JSON with doc.toJSON() and restored with PdfDocument.fromJSON(json) (see Creating documents).
Creating documents
Pages and the flow
new PdfDocument(options) starts an empty document. The flow methods add the first page by themselves; addPage({ format, orientation, margins }) adds a page with its own size and makes it the current page of the flow. Formats: ISO A0 to A10 (default 'A4'), B0 to B10, envelopes C0 to C10 and 'DL', 'Letter', 'Legal', 'Tabloid', 'Ledger' (a Tabloid sheet across: use it with orientation: 'landscape', a portrait page turns it into Tabloid), 'Executive', 'Statement', or [width, height] in pt. Names are case-insensitive ('a6'). An unknown name throws a RangeError with code: 'page-format' (in the document options, addPage, insertPage, templates). FORMATS has the sizes, pageFormatName(name) returns the standard spelling of a name (or null), resolvePageSize(format, orientation) computes a size.
const book = new VibeFoxJSPdf.PdfDocument({ format: 'A5', font: { family: 'times', size: 11 } });
book.text('Chapter 1', { size: 18, bold: true, marginBottom: 8 });
book.text('A long paragraph wraps inside the margins and continues on the next page when the page is full.', { align: 'justify' });
book.moveDown(20); // empty space, pt
book.ensureSpace(120); // a new page unless 120 pt are left
book.addPage({ format: 'a4', orientation: 'landscape' });
console.log(VibeFoxJSPdf.pageFormatName('a6')); // 'A6'
try { book.addPage({ format: 'A11' }); } catch (e) { console.log(e.code); } // 'page-format'
book.setCursorY(200); // continue the flow at y 200 of the current page
book.text('A wide page.');
Flow methods: text(text, options), image(src, options), svg(svg, options), table(options), addHtml(html, options), addComponent(component, options); cursor: cursor ({ page, y }), currentPage, setCursorY(y), moveDown(dy), ensureSpace(h). Pages: pages, pageCount, page(i); a page knows its width, height, margins, contentWidth, contentHeight and index.
Text
Options of doc.text() (flow) and page.text() (placed): font, size (pt, default 12), bold, italic, color, align ('start' — default, 'end', 'left', 'center', 'right', 'justify'; start and end follow the direction of the paragraph), dir ('auto' — default, 'ltr', 'rtl'; see Right-to-left and complex scripts), lineHeight (default 1.35), opacity, kerning, ligatures; in the flow also indent, width, paragraphGap, marginBottom; on a page x, y, width and rotate (degrees, one line). A line break \n starts a new paragraph. page.text() returns the box it took ({ x, y, width, height, bottom, lines }); page.measureText(text, { font, size, bold, dir }) measures a string without drawing it.
const p = doc.page(0);
const box = p.text('Total: 1 250.00 EUR', { x: 350, y: 700, width: 195, align: 'right', size: 14, bold: true });
p.drawLine(350, box.bottom + 4, 545, box.bottom + 4, { color: '#94a3b8', width: 0.5 });
p.text('PAID', { x: 420, y: 760, size: 28, color: '#16a34a', rotate: 15, opacity: 0.6 });
console.log(p.measureText('Total', { size: 14, bold: true })); // width in pt
Shapes and paths
Page methods: drawLine(x1, y1, x2, y2, { color, width, dash, opacity }), drawRect(x, y, w, h, { fill, stroke, lineWidth, dash, opacity, radius }), drawEllipse(cx, cy, rx, ry, style), drawCircle(cx, cy, r, style), drawPolygon(points, { close, …style }) and drawPath(segments, style) with the segments M, L, C, Q and Z. group(options, fn) (or beginGroup / endGroup) draws a part of the page with a transform matrix, a clip path and one opacity; groups nest.
const pg = doc.page(0);
pg.drawCircle(80, 760, 20, { fill: '#fde68a', stroke: '#b45309', lineWidth: 1.5 });
pg.drawPolygon([[130, 780], [150, 740], [170, 780]], { fill: '#bfdbfe', close: true });
pg.drawPath([{ c: 'M', x: 200, y: 780 }, { c: 'C', x1: 220, y1: 730, x2: 260, y2: 790, x: 280, y: 750 }], { stroke: '#7c3aed', lineWidth: 2 });
pg.group({ opacity: 0.5, clip: [{ c: 'M', x: 300, y: 740 }, { c: 'L', x: 360, y: 740 }, { c: 'L', x: 360, y: 780 }, { c: 'L', x: 300, y: 780 }, { c: 'Z' }] }, (g) => {
g.drawRect(290, 730, 90, 60, { fill: '#ef4444' });
});
Images and SVG
JPEG and PNG (every color type, with transparency) are taken as bytes (Uint8Array, ArrayBuffer), a data URL or the id of addImage(), which registers an image once for many places. doc.image(src, { width, height, align, opacity }) puts one into the flow keeping its proportions; page.drawImage(src, x, y, { width, height }) places it and returns the size it got. Other formats (GIF, WebP) are not read: draw them into a canvas and pass its PNG.
SVG is drawn as vector graphics, not as a picture: doc.svg(svg, { width, align }) in the flow, page.drawSvg(svg, x, y, { width, height }) on a page. The input is SVG markup, its bytes or an <svg> element. Shapes, paths, strokes and dashes, transforms, gradients, clip paths, markers, <use>, text (with your registered fonts), embedded PNG / JPEG images and the CSS of <style> are supported; masks, filters, patterns and <foreignObject> are skipped with a warning (onWarning, else one console warning; the document emits warning).
const logo = doc.addImage(logoPng); // a PNG data URL, registered once
doc.page(1).drawImage(logo, 50, 60, { width: 48 });
doc.image(logo, { width: 120, align: 'center', marginBottom: 12 });
doc.svg(`<svg xmlns="http://www.w3.org/2000/svg" width="300" height="120">
<defs><linearGradient id="g"><stop offset="0" stop-color="#0ea5e9"/><stop offset="1" stop-color="#6366f1"/></linearGradient></defs>
<rect x="10" y="10" width="280" height="100" rx="12" fill="url(#g)"/>
<text x="150" y="70" text-anchor="middle" font-size="28" fill="#fff">Vector</text>
</svg>`, { width: 240, align: 'center' });
Tables
doc.table(options) lays out a table in the flow: the text of the cells wraps, rows go to the next page, and the header is repeated there (repeatHeader, default true). Columns are { header, field, width, align, format(value, row) } (width in pt or 'auto'); without columns they are taken from the keys of the rows. Rows are objects or arrays. Look: fontSize, font, color, cellPadding, borderColor, borderWidth, zebra (fill of every other row), headerStyle: { fill, color, bold }, x and width. It returns { y, pages, rows }.
const res = doc.table({
columns: [
{ header: 'Item', field: 'item' },
{ header: 'Qty', field: 'qty', width: 50, align: 'right' },
{ header: 'Amount', field: 'amount', width: 90, align: 'right', format: (v) => v.toFixed(2) },
],
rows: Array.from({ length: 80 }, (_, i) => ({ item: `Item ${i + 1}`, qty: i % 5 + 1, amount: (i + 1) * 9.5 })),
zebra: '#f8fafc',
headerStyle: { fill: '#0f766e', color: '#ffffff' },
fontSize: 9,
});
console.log(res.pages, res.rows);
Barcodes (QR, Data Matrix, Code 128, EAN-13, EAN-8, UPC-A, Code 39, ITF, ITF-14) and tables bound to data are elements of templates (see Templates and the designer).
Header, footer and watermark
The options header and footer (or setHeader() / setFooter()) print a line in the top / bottom margin of every page: a text with the placeholders {page}, {pages}, {title} and {date}, or { text, align, size, color, font, bold }. watermark / setWatermark(text, { size, color, opacity, angle, font, bold }) draws a text across every page; null removes it. They also apply to the pages of opened files.
doc.setHeader({ text: '{title}', align: 'left', size: 9, color: '#64748b' });
doc.setFooter({ text: 'Page {page} of {pages}', align: 'right', size: 9 });
doc.setWatermark('DRAFT', { opacity: 0.12, angle: 45, size: 90 });
Links, bookmarks and metadata
const pageOne = doc.page(0);
pageOne.link(50, 100, 200, 16, { url: 'https://example.com/terms' }); // external link
pageOne.link(50, 120, 200, 16, { page: 2, destY: 0 }); // to the third page
const chapter = doc.addBookmark('Terms', { page: 1 });
doc.addBookmark('Payment', { page: 1, y: 300, parent: chapter }); // nested bookmark
doc.setMetadata({ title: 'Invoice 2026-001', author: 'Example Ltd', subject: 'Invoice', keywords: 'invoice, 2026' });
The bookmarks are in doc.outline; the viewer shows them in its sidebar.
Saving
| Method | Returns | Description |
|---|---|---|
toBytes(options) | Promise<Uint8Array> | The PDF file. Options: compress, incremental (opened files), encrypt, pdfa, pdfua, tagged for this output only. |
save(filename) | Promise<Uint8Array> | Browser: downloads the file; Node: writes it. Emits save. |
toDataURL(options) | Promise<string> | A data:application/pdf;base64,… URL. |
toBlobURL(options) | Promise<string> | A blob: URL (browser), for example for a new tab. |
The file is PDF 1.7. Content streams are compressed when the platform has CompressionStream (compress: 'auto', default).
JSON snapshots and merging
doc.toJSON() is the whole document as JSON (pages with their drawing, images, fonts as base64, bookmarks, annotations, form fields); PdfDocument.fromJSON(json) restores it — for storing a document, sending it to a server or changing it later. toJSON({ fonts: false }) leaves the font files out; give them back with fromJSON(json, { fonts: [{ family, data }] }). PdfDocument.merge(a, b, …) makes one document of several (documents of the library and opened files): pages, images, fonts, bookmarks, form fields and annotations come along.
const json = JSON.stringify(doc.toJSON());
const copy = VibeFoxJSPdf.PdfDocument.fromJSON(JSON.parse(json));
const both = VibeFoxJSPdf.PdfDocument.merge(doc, copy);
console.log(both.pageCount); // 6
A snapshot of an opened file keeps only the drawing added with the library, not the original pages; save such documents as PDF bytes.
Fonts
The library ships no font files. It has the 14 standard PDF fonts, which every PDF reader has, and it embeds the font files you give it.
Standard fonts
The families 'helvetica' (default), 'times' and 'courier' with bold and italic, plus 'symbol' and 'zapfdingbats'. The text of the first three is Latin (Windows-1252) and Cyrillic (Windows-1251); one line may mix both. 'symbol' has Greek letters and mathematical signs, 'zapfdingbats' has dingbats (check marks, crosses, circled numbers, arrows …): write their text with the Unicode characters (Greek letters, ∑, ∞, the check mark U+2714, circled digits …) or with the letter codes of their encodings (a, b, g = α, β, γ; 4 = the check mark). The viewer shows them as the saved file does, and text extraction and search give the Unicode characters. Any other character (CJK, Arabic, Hebrew, ₽ …) needs a font file of yours: without one it is written as ?. Standard fonts are not embedded, so they cannot be used in PDF/A (see PDF/A, PDF/UA and tagged PDF).
Your own fonts
registerFont(family, bytes, { weight, style, index, kerning }) embeds a TrueType or OpenType font (.ttf, .otf with TrueType or CFF outlines, one face of a .ttc); await loadFont(family, source, options) does the same from a URL, a Blob or bytes and also reads .woff (WOFF2 is not read — convert it to .ttf / .otf / .woff). The option fonts: [{ family, data, weight, style }] of the document registers them at once. A registered family is a font value everywhere: flow and page text, tables, headers and footers, watermarks, SVG text, HTML, form fields, templates.
const intl = new VibeFoxJSPdf.PdfDocument();
await intl.loadFont('Noto Sans', 'fonts/NotoSans-Regular.ttf');
await intl.loadFont('Noto Sans', 'fonts/NotoSans-Bold.ttf', { weight: 700 });
intl.text('Grüße · Привет · Cześć', { font: 'Noto Sans', size: 14 });
intl.text('A bold heading', { font: 'Noto Sans', bold: true });
console.log(intl.getFonts().map((f) => `${f.family} ${f.weight} ${f.style}`), intl.hasFont('Noto Sans'));
- Only the glyphs you use are written (a subset), with a ToUnicode map, so the text can be selected, copied and searched in any reader.
- Kerning of the font (GPOS or kern table) is applied and measured; turn it off with
kerning: falseon the face, the text or the document optionfont.kerning. boldanditalicpick the closest registered face; register the bold / italic files for real bold / italic (no synthetic styles).- Fallback chain:
setFallbackFonts([...families])(or the optionfallbackFonts) lists registered families tried in order for characters the font of a text does not have, for example a CJK font after a Latin one. Set it before adding text. - Chinese, Japanese and Korean text breaks between characters, without spaces, with the basic line-breaking rules.
- Standard ligatures of the font (fi, fl …) are applied; turn them off with
ligatures: falseon the text or the document optionfont.ligatures.
Right-to-left and complex scripts
Text with a font file of yours is shaped and ordered as a browser does it: right-to-left text (Arabic, Hebrew, Persian, Urdu) is laid out right to left with the Unicode bidirectional algorithm, numbers and Latin words inside it keep their order, Arabic letters join, Devanagari (Hindi, Marathi, Nepali) is built into syllables (conjuncts, reph, vowel signs), marks and vowel points are placed by the font, and the font's ligatures and kerning apply. The standard fonts have no Arabic, Hebrew or Indic letters: register a font that has them.
dir—'auto'(default: by the first strong letter of each paragraph),'ltr'or'rtl'— ondoc.text,page.text,page.measureText,doc.tableand as a document option (the default of text, tables and templates).align: 'start'(default) is right in a right-to-left paragraph,'end'left;indentis on the right; the last line of a justified paragraph goes right.- Tables with
dir: 'rtl'have the first column on the right; the defaultalignof a column is'start'. - Lines are broken in logical order and then reordered; a word is never cut inside a letter cluster.
- The text stays logical in the file: copying from any reader,
extractText, search and redaction give the text in reading order (also for files of other programs).
const ar = new VibeFoxJSPdf.PdfDocument({ dir: 'rtl' });
await ar.loadFont('Noto Naskh Arabic', 'fonts/NotoNaskhArabic-Regular.ttf');
await ar.loadFont('Noto Sans Hebrew', 'fonts/NotoSansHebrew-Regular.ttf');
ar.text('مرحبا بالعالم — الطلب رقم 42', { font: 'Noto Naskh Arabic', size: 16 }); // right-aligned, joined
ar.text('שלום עולם', { font: 'Noto Sans Hebrew', align: 'end' }); // end = left in RTL
ar.table({ font: 'Noto Naskh Arabic', columns: [{ header: 'المنتج', field: 'p' }, { header: 'الكمية', field: 'q' }], rows: [{ p: 'قلم', q: 3 }] });
The same engine writes the text of HTML to PDF, of templates and of the PDF export of the other VibeFox JS libraries (with their embedded fonts). The library files switch it on when they load. If your own build tool takes the readable vibefox-js-pdf.esm.js and drops unused code, the engine stays in your build only when your code names enableComplexScripts or complexScripts: call VibeFoxJSPdf.enableComplexScripts() once; without it right-to-left text is written in logical order and a warning says so.
HTML to PDF
htmlToPdf(html, options) makes a new document from HTML; doc.addHtml(html, options) lays HTML out into the flow of a document (from the cursor; the flow continues after it). The input is an HTML string, its bytes, or — in the browser — a live element: then the computed styles of the page apply. The library has its own HTML parser and CSS cascade, so an HTML string also works in Node.
const html = `<style>
h1 { color: #0f766e; }
table { border-collapse: collapse; width: 100%; }
td, th { border: 1px solid #cbd5e1; padding: 4px 8px; }
</style>
<h1>Quarterly report</h1>
<p>Revenue grew by <b>12 %</b>. Details: <a href="https://example.com/q3">example.com/q3</a>.</p>
<table><thead><tr><th>Region</th><th>Sales</th></tr></thead>
<tbody><tr><td>North</td><td>120</td></tr><tr><td>South</td><td>98</td></tr></tbody></table>`;
const report = await VibeFoxJSPdf.htmlToPdf(html, {
format: 'A4',
footer: '<p style="text-align: right">{page} / {pages}</p>',
});
const result = await doc.addHtml('<h2>Notes</h2><ul><li>First</li><li>Second</li></ul>', { newPage: true });
console.log(report.pageCount, result.pages, result.warnings);
| Option | Type | Default | Description |
|---|---|---|---|
css | string | — | CSS added after the <style> elements (HTML strings). |
header, footer | string or { html, gap } | — | HTML in the top / bottom margin of every page of the call; {page} {pages} {title} {date}. |
bookmarks | boolean or number | htmlToPdf: true, addHtml: false | Headings h1–h6 (or up to a level) as nested bookmarks. |
forms | boolean | true | Inputs, check boxes, radio buttons, selects, text areas and buttons become PDF form fields; false draws them with their values. |
fontSize, fontFamily, color | number, string | 12 pt, the document font | Root font size (12 pt = 16 CSS px), family and text color. |
baseUrl | string | — | Base of relative links, images and fonts. |
resolveImage(src) | function | — | Bytes / data URL / SVG markup of an image the library cannot fetch (Node). |
newPage | boolean | false | Start on a new page. |
repeatHeader | boolean | true | Repeat <thead> rows on every page of a table. |
title | boolean | true | <title> becomes the document title. |
locale | string | — | Locale of {date}. |
onWarning(message) | function | one console warning | Unsupported HTML / CSS. |
Supported: block and inline layout with margins, paddings, borders (solid, dashed, dotted, double), rounded corners, background colors; fonts by font-family (your registered families or the standard ones: serif → Times, monospace → Courier, others → Helvetica); text decoration, alignment, indents, white-space; lists of every common numbering; tables with column and row spans, collapsed or separate borders, repeated header rows; images (PNG, JPEG, SVG; other formats through a canvas in the browser); links (http(s), mailto, tel, #anchors); page breaks with break-before, break-after, break-inside: avoid; CSS @page { size; margin } for htmlToPdf; @font-face with TTF / OTF / WOFF; custom properties and calc(). Laid out in the flow with a warning: flex and grid, floats, absolute / fixed positions, transforms, shadows, background images and gradients, multiple columns, ::before / ::after content; <link rel="stylesheet"> is not loaded (put the CSS into css).
Right to left: the dir attribute (ltr, rtl, auto) and CSS direction; text-align: start / end (also in cells and list items); margin, padding and border -inline-start / -inline-end (and the -inline shorthands) follow the direction of the element, and of a logical and a physical property the later one wins, as in a browser; tables of an RTL element have the first column on the right; lists are indented on the right with their markers on the right (outside and inside); a block or table with a set width stands at the right edge. @page { size } takes every format name of the library.
VibeFox JS components in a PDF
await doc.addComponent(component, options) draws a component of another VibeFox JS library — a chart, a grid, a diagram, a Gantt chart, an editor document, a trading chart — into the document as vector graphics: in the flow (the content width and the on-screen aspect ratio) or at { page, x, y, width, height }. It works with whatever export the component has (its PDF drawing, its SVG, its own PDF file); components with only a picture export are placed as an image (kind: 'image'). Text drawn by the component uses the fonts registered in this document (right-to-left text and Arabic, Hebrew or Devanagari labels are shaped and ordered, see Right-to-left and complex scripts). VibeFox JS PDF does not need the other library for this; you only pass a component that is already on the page.
// VibeFox JS Charts is also on the page (its file loaded)
const chart = VibeFoxJSCharts.createChart('#app', { categories: ['A', 'B', 'C'], series: [{ type: 'column', data: [5, 8, 3] }] });
const report = new VibeFoxJSPdf.PdfDocument();
report.text('Sales by product', { size: 16, bold: true, marginBottom: 8 });
const placed = await report.addComponent(chart, { height: 220 });
console.log(placed.kind, placed.via, placed.pageIndex);
await report.addComponents([chart, chart], { columns: 2, gap: 12, height: 160 }); // a layout grid
addComponents(items, { columns, gap, height, marginBottom }) lays several out in a grid (items may be { component, span, height, options }); addPageFrom(component) appends all pages of the component's own PDF export (a long table, a document with its headings as bookmarks) in the page size of this document; options of each call go to the export of the component (title, legend, …).
Opening and changing PDF files
await loadPdf(input, options) opens an existing PDF: bytes, a Blob / File, a URL or a data URL. The result is a PdfDocument whose pages are the pages of the file; everything of the builder works on them (text, shapes, images, SVG, fonts, links, form fields, header, footer and watermark on every page), new pages can be added, and the metadata can be changed.
const pdf = await VibeFoxJSPdf.loadPdf(file); // a File from <input type="file">
console.log(pdf.pageCount, pdf.sourceInfo.version, pdf.metadata.title);
pdf.page(0).text('APPROVED', { x: 400, y: 40, size: 18, bold: true, color: '#16a34a' });
pdf.setWatermark('COPY', { opacity: 0.1 });
pdf.setMetadata({ subject: 'Approved copy' });
const updated = await pdf.toBytes(); // incremental update: the original bytes stay unchanged
const compact = await pdf.toBytes({ incremental: false }); // a new compact file
- Drawing on an opened page uses the page as shown (its crop box and rotation): (0, 0) is the top-left corner the reader sees.
- Saving writes an incremental update by default: the original bytes followed by the changes (nothing changed = the same bytes).
incremental: falsewrites a new file without removed pages and old revisions. - Read: every cross-reference kind, object streams, chains of updates, damaged files (rebuilt by scanning;
sourceInfo.repaired), files with junk before the header. - Encrypted files open with the user password (usually empty) or the owner password (
{ password }): RC4, AES-128, AES-256. They are saved with the same encryption. The permissions are reported (sourceInfo.encrypted.allowed), not enforced while you work with the document. - Signed files:
sourceInfo.signed,signatures,certified. An incremental save keeps the signatures (readers list the later changes);incremental: falsebreaks them; a warning is given.
sourceInfo (null for documents made with the library): { version, pageCount, size, xref, updates, repaired, encrypted, signed, certified, signatures, warnings }. Errors of loadPdf have a code: 'not-pdf', 'damaged', 'encrypted' (an encryption that is not supported, such as certificates), 'password' (missing or wrong).
try {
const secret = await VibeFoxJSPdf.loadPdf(pdfBytes, { password: 'secret', onWarning: (m) => console.warn(m) });
console.log(secret.sourceInfo.encrypted);
} catch (e) {
if (e.code === 'password') console.log('Ask the user for the password');
else throw e;
}
parsePdf(bytes) is a quick reader of the version, page count, encryption flag and metadata of simple files; loadPdf is the full reader.
Page operations
These methods work on documents of the library and on opened files alike; links and bookmarks follow the pages they point to.
| Method | Returns | Description |
|---|---|---|
insertPage(index, { format, orientation, margins }) | PdfPage | A new empty page at index. |
removePage(index) | this | Remove a page (emits pageRemove). |
movePage(from, to) | this | Move a page. |
rotatePage(index, angle), page.setRotation(angle) | this | Turn a page by a multiple of 90° (relative / absolute); the drawing coordinates do not change. |
copyPages(src, indices, { at }) | PdfPage[] | Copy pages of another document (or duplicate pages of this one) with their images, fonts, links, fields and annotations. |
extractPages(pages) | PdfDocument | A new document with these pages (0-based indexes or a range string '1-3, 7'), their bookmarks and metadata. |
split(spec) | PdfDocument[] | Several documents: { every: n }, { ranges: '1, 2-5, 6-' } or { bookmarks: level } (a part per bookmark, titled after it). |
PdfDocument.merge(...docs) | PdfDocument | One document of several; form fields with the same name get name_2, … |
page.drawPage(src, index, x, y, { width, height, align }) | box | Draw a page of any document into a box as vectors (several pages on one sheet, imposition). |
const pdf = await VibeFoxJSPdf.loadPdf(pdfBytes);
pdf.rotatePage(0, 90);
pdf.movePage(2, 0);
pdf.removePage(1);
const firstTwo = doc.extractPages('1-2');
const single = doc.split({ every: 1 }); // one document per page
const all = VibeFoxJSPdf.PdfDocument.merge(firstTwo, pdf);
// two pages on one landscape sheet
const sheet = new VibeFoxJSPdf.PdfDocument({ margins: { top: 0, right: 0, bottom: 0, left: 0 } });
const s = sheet.addPage({ orientation: 'landscape' });
s.drawPage(doc, 0, 20, 20, { width: 390, height: 555 });
s.drawPage(doc, 1, 432, 20, { width: 390, height: 555 });
console.log(single.length, all.pageCount);
In the viewer the same operations are available with the mouse and the keyboard (see Viewer → Page editing).
Viewer
createPdfViewer(target, options) shows a PdfDocument — one you are building (it follows every change at once) or a file opened with loadPdf(). setDocument(doc, { page }) shows another one (at page 1, or at page), getDocument() returns it, null shows "No document". The toolbar has the sidebar button, the page field, previous / next, zoom out / in, fit width, rotate, search, print and download (toolbar: false hides it).
const v = VibeFoxJSPdf.createPdfViewer('#app', {
document: doc,
page: 2, // opened at page 2 (1-based)
zoom: 1, // 1 = 100 %; minZoom 0.25, maxZoom 4
layout: 'continuous', // every page in one scroll; 'single' = one page at a time
sidebar: 'thumbnails', // 'thumbnails' | 'outline' | 'layers' | 'signatures' | null
filename: 'invoice.pdf', // name of the downloaded file
style: 'classic', // ready-made look (see Theming and styling)
});
v.fitWidth();
v.rotate(90); // turns the view, not the document
console.log(v.getState()); // { page: 2, zoom: …, style: 'classic', rotation: 90, sidebar: 'thumbnails' }
Navigation and zoom
Methods: goToPage(n) (1-based), nextPage(), prevPage(), setZoom(zoom), zoomIn(), zoomOut(), fitWidth(), fitPage(), rotate(delta), setRotation(angle), getRotation(), refresh(), download(); the option page opens that page when the viewer is created (without a pageChange event), setOptions({ page }) turns to it like goToPage, setOptions({ document, page }) shows another document at that page; events pageChange, zoomChange, rotationChange, documentChange, renderComplete (per drawn page). In the continuous layout the current page follows the scrolling. Only the pages in view (and one before / after) are drawn, so files with thousands of pages scroll smoothly; pages are drawn sharp on high-density screens, and a deep zoom draws the visible part in full resolution.
Sidebar: thumbnails, bookmarks, layers, signatures
showSidebar(view), hideSidebar(), toggleSidebar() and the option sidebar open a panel with tabs (icons; the name is the tooltip and the name for screen readers; the variable --vfjs-pdf-tab-label-display: inline shows the names next to the icons, the tabs then wrap): 'thumbnails' (drawn lazily, the current page marked), 'outline' (the bookmarks of the file and those of addBookmark() as a tree; a click opens the page), 'layers' (only for files with optional content: check boxes per layer; locked layers and radio groups as the file defines them) and 'signatures' (only for signed files, see Digital signatures). Event sidebarChange.
const layers = viewer.getLayers(); // [{ id, name, visible, locked, level, radio }]
if (layers.length) viewer.setLayerVisible(layers[0].name, false); // pages and thumbnails follow
viewer.on('layersChange', (e) => console.log(e.layers.filter((l) => l.visible).map((l) => l.name)));
Text selection and search
A transparent text layer over the pages (textLayer: true, default) makes the text selectable and copyable. The search bar opens with Ctrl+F or the toolbar button; from code: search(query, { caseSensitive, wholeWord }) highlights every match and shows the first one at / after the current page, searchNext() and searchPrev() move (and wrap), clearSearch(), getSearch(), showSearch(), hideSearch(); event searchChange. White space in the query matches any white space or line break. getPageText(n) returns the text of a page as the search sees it.
const state = await viewer.search('invoice', { caseSensitive: false });
console.log(state.total, state.index, state.page); // matches, current match (0-based), its page
viewer.searchNext();
console.log(await viewer.getPageText(1));
Page editing
With pageEditing: true the thumbnail panel gets a page tool bar (rotate left / right, move up / down, delete, insert a PDF file, undo, redo): select thumbnails with a click (Ctrl / Cmd + click, Shift + click for ranges), drag them to a new place, drop a PDF file from the desktop onto the panel to insert its pages. The same from code (also without the option), each step undoable:
const ed = VibeFoxJSPdf.createPdfViewer('#app2', { document: await VibeFoxJSPdf.loadPdf(pdfBytes), pageEditing: true, sidebar: 'thumbnails' });
ed.selectPages([0, 1]);
ed.rotatePages(); // the selected pages, 90° clockwise
ed.movePages([2], 0); // page 3 to the front
await ed.insertPages(file, { at: 1, pages: '1' }); // the first page of another PDF file after page 1
ed.removePages([3]);
ed.undo();
ed.on('pageEdit', (e) => console.log(e.action, e.pages));
Methods: selectPages, getSelectedPages, rotatePages(indices, angle), removePages(indices), movePages(indices, to), insertPages(source, { at, pages, password }), undo, redo, canUndo, canRedo; events pageEdit, pageSelectionChange, pageInsertError. The last page is never deleted. The changes are changes of the document: save it as usual.
Printing
The print button of the toolbar (between search and download) and print(options) print the document through the browser's print dialog. The pages are drawn as images at a print resolution into a hidden frame of your page: no window opens, the viewer does not change, and the frame is removed after printing. Only annotations meant for printing are included — annotations with print: false are left out, and annotations: false leaves all out; form values and the visible layers are printed as shown.
const result = await viewer.print({
pages: '1-2', // 'all' (default), 'current', '1-3, 5, 8-' or [1, 3]
dpi: 200, // default 150, 72 … 600
onProgress: (e) => console.log(`page ${e.page}: ${e.done} of ${e.total}`),
});
console.log(result); // { pages: [0, 1], total: 2, dpi: 200 } after the dialog
viewer.on('printProgress', (e) => console.log(e.done, e.total));
console.log(viewer.canPrint());
- Options:
pages,dpi,title(of the print job; default: the document title, elsefilename),annotations,renderer,worker,signal(anAbortSignal),onProgress. The promise resolves after the dialog (nullwithout a document). - While the pages are prepared, the button shows "Cancel printing" and the notice line the progress;
cancelPrint()or a newprint()cancels (the promise rejects with anAbortError,code: 'abort'). Events:printProgress { page, done, total }after each page,print { pages, total, window }right before the dialog. - Permissions of opened files apply: a file encrypted with printing not allowed and opened without the owner password cannot be printed (
canPrint()isfalse, the button is disabled,print()rejects withcode: 'permission'); without the high-quality permission the resolution is at most 150 dpi. Other errors:code: 'renderer'(renderer: 'pdfjs'without pdf.js), aRangeErrorfor pages out of range. - With
forms: true, a form button with the action'print'prints throughprint().
Drawing a page without the viewer
await renderPageToCanvas(doc, pageIndex, canvas, options) draws one page (0-based) into a canvas: scale (CSS pixels per pt), background, annotations, fields, intent: 'print' (only annotations meant for printing), layers, region (a tile of a large page), renderer, signal (an AbortSignal). It resolves to { width, height, original, renderer }.
const canvas = document.createElement('canvas');
const info = await VibeFoxJSPdf.renderPageToCanvas(doc, 0, canvas, { scale: 0.5, background: '#ffffff' });
console.log(info.width, info.height); // a thumbnail of page 1
document.body.append(canvas);
Rendering PDF files
Pages made with the library are drawn from their own drawing commands. The original content of opened files is drawn by the library's own PDF renderer, so the viewer, the thumbnails, the text layer, the search, the layers panel, the visual comparison and the base PDF of the designer need nothing else. It covers the content of ISO 32000-1: every graphics and text operator, all font kinds (TrueType, Type 1, CFF, Type 3, CID fonts; embedded fonts are given to the browser as fonts), every color space, shadings, patterns, soft masks, blend modes, transparency groups, optional content (layers), annotation appearances and form widgets, and the image formats Flate, LZW, RunLength, JPEG, JPEG 2000, CCITT and JBIG2.
- Speed, measured in headless Chrome on a 1202-page manual at scale 1.5: the file opens in 15 ms; drawing all 1202 pages one after another takes 3.8 s (median 2.9 ms per page); the text of all pages for a search takes 0.89 s. The viewer draws only the pages in view.
- Work is split into time slices, so the page stays responsive; renders of pages that leave the view are cancelled.
- A Web Worker: by default the renderer runs in a worker that loads the same library file (over
http(s)), with a silent fallback to the main thread.useLiteWorker(false)turns it off;useLiteWorker({ url, type })gives the URL of the library file when it cannot be found by itself (a renamed or inlined file). - Memory: decoded images, parsed content and fonts are cached per opened file, 64 MB by default;
liteCacheLimit(bytes)changes the budget (0 = no cache) and returns the previous one.
The renderer option and pdf.js
The option renderer of the viewer, the comparison view, the designer, renderPageToCanvas and comparePdf chooses what draws the original content of opened files: 'auto' (default: pdf.js when you connected it, else the own renderer), 'lite' (always the own renderer) or 'pdfjs' (only pdf.js; without it a notice line says that only the drawing added with the library is shown). pdf.js is never part of the library: connect your own copy with usePdfJs(pdfjsLib, { workerSrc, cMapUrl, standardFontDataUrl, wasmUrl }) for every viewer, or with the option pdfjs of one viewer (its namespace or the URL of pdf.mjs, imported on first use); usePdfJs(null) disconnects it.
VibeFoxJSPdf.createPdfViewer('#app2', { document: await VibeFoxJSPdf.loadPdf(pdfBytes), renderer: 'lite' });
VibeFoxJSPdf.useLiteWorker(true); // default
const previous = VibeFoxJSPdf.liteCacheLimit(32 * 1024 * 1024);
Low-level functions
await renderPageLite(page, canvas, options) paints the original content of one page of an opened file with the own renderer into a canvas or an OffscreenCanvas (scale, pixelRatio, background, annotations, forms, intent, layers, region, timeSlice, signal; text: true also returns the text items with their positions) and reports what it could not draw in unsupported. layersLite(doc) lists the optional content groups of an opened file.
const opened = await VibeFoxJSPdf.loadPdf(pdfBytes);
const c = document.createElement('canvas');
const r = await VibeFoxJSPdf.renderPageLite(opened.page(0), c, { scale: 1, text: true });
console.log(r.width, r.height, r.unsupported, r.text.length, VibeFoxJSPdf.layersLite(opened));
Text extraction and search
The text of any document — pages made with the library and opened files — is read by the library itself, in the browser and in Node. await doc.extractText({ pages }) returns { text, pages: [{ page, text }] }; await doc.searchText(query, { pages, caseSensitive, wholeWord }) returns the matches with their boxes on the page ([{ page, text, rects }], page pt). A query is a text, a regular expression or one of the ready-made patterns 'email', 'phone' and 'card' (REDACTION_PATTERNS).
const { text, pages } = await doc.extractText();
console.log(pages.length, text.slice(0, 80));
const hits = await doc.searchText(/\d+\.\d\d EUR/);
console.log(hits.map((h) => `${h.page + 1}: ${h.text}`));
const emails = await doc.searchText('email');
Text order is the drawing order of the content; the text of annotations is not included.
Annotations
Annotations are comments drawn over the pages and saved as real PDF annotations with their appearance, so every PDF reader shows them; files saved by the library read back without loss. Types (ANNOTATION_TYPES): 'highlight', 'underline', 'strikeout', 'squiggly', 'ink', 'rect', 'ellipse', 'line' (arrows with line ends), 'polyline', 'polygon', 'note' (with replies), 'freetext', 'stamp' and 'signature'.
From code
doc.addAnnotation(0, { type: 'highlight', rects: [[50, 56, 150, 22]], text: 'Check this number', author: 'Anna' });
doc.addAnnotation(0, { type: 'note', x: 500, y: 100, text: 'Please confirm the total.' });
doc.addAnnotation(0, { type: 'rect', rect: [45, 50, 220, 40], color: '#dc2626', width: 2 });
doc.addAnnotation(0, { type: 'line', points: [[300, 200], [400, 150]], arrow: true, color: '#2563eb' });
doc.addAnnotation(0, { type: 'freetext', rect: [300, 220, 200, 40], text: 'Updated in March', fontSize: 11 });
const stamp = doc.addAnnotation(0, { type: 'stamp', stamp: 'approved', x: 380, y: 60 });
doc.updateAnnotation(stamp.id, { rect: [380, 60, 160, 40] }); // move / resize
console.log(doc.getAnnotations({ page: 0 }).map((a) => a.type));
An annotation is plain JSON data: { id, type, rect: [x, y, w, h], color, fill, opacity, width, dash, text, author, subject, created, modified, … } plus the fields of its type (quads or rects of text markup, paths of ink, points and lineEnds, icon and replies of notes, font / fontSize / align of text boxes, stamp / label / image of stamps). Ready-made stamps (PDF_STAMPS, labels in the language files): approved, notApproved, rejected, draft, final, confidential, topSecret, forComment, reviewed, received, paid, void, expired, copy; or your own label or image.
Document methods: addAnnotation(page, data), getAnnotations({ page, type }), getAnnotation(id), updateAnnotation(id, patch), removeAnnotation(id); the same on a page (page.addAnnotation(data), …). Events of the document: annotationAdd, annotationChange, annotationRemove. Annotations of opened files are read too: the common types can be edited; others (stamps of other programs, attachments, …) are readOnly — they keep their look and can be commented on or removed.
Exchange and flattening
const json = doc.exportAnnotations(); // { v: 1, annotations: [...] }, images as data URLs
const xfdf = doc.exportAnnotations({ format: 'xfdf' }); // the XML exchange format of PDF readers
const copy = VibeFoxJSPdf.PdfDocument.fromJSON(doc.toJSON());
copy.importAnnotations(xfdf, { replace: true });
copy.flatten({ annotations: true, forms: true }); // annotations, signatures and fields become page content
In the viewer
Annotations are always shown. annotations: true adds the annotation toolbar (tools, 8 colors, line width, opacity, undo, redo, delete) and editing: select, move, resize, edit notes and text boxes. annotationTools limits the tools (PDF_ANNOTATION_TOOLS: 'select', 'highlight', 'underline', 'strikeout', 'squiggly', 'ink', 'rect', 'ellipse', 'line', 'arrow', 'polyline', 'polygon', 'note', 'freetext', 'stamp', 'signature'), author is written into new annotations.
- Text markup: select text and pick the tool (or pick the tool and select); on pages without text, or with Alt, drag a box.
- Ink: draw with the mouse, a pen or a finger; strokes within 2 seconds join one annotation.
- Shapes: drag (Shift keeps squares and 45° lines); polylines and polygons: click the points, double click or Enter ends.
- Note: click to place, then a popup with the text and the replies; text box: drag a box and type.
- Stamps: a menu of the ready-made stamps and "own image"; the stamp follows the pointer until a click puts it down.
const av = VibeFoxJSPdf.createPdfViewer('#app2', { document: doc, annotations: true, author: 'Anna', annotationTools: ['select', 'highlight', 'note', 'stamp'] });
av.setTool('highlight');
av.on('annotationAdd', (e) => console.log(e.annotation.type, e.page));
av.placeStamp({ stamp: 'paid' }); // follows the pointer until a click
av.setTool('select');
Methods: setTool, getTool, selectAnnotation(id), getSelectedAnnotation, deleteAnnotation(id), editAnnotation(id), placeStamp(options), undo, redo, canUndo, canRedo (100 steps); events toolChange, annotationSelect, historyChange, stampPlace, annotationAdd, annotationChange, annotationRemove.
Visual signatures
A visual signature is a picture of a handwritten signature placed on a page (for cryptographic signatures see Digital signatures). Signature data is { kind: 'draw' | 'text' | 'image', paths | text + image | image, width, height, color }: drawnSignature(strokes) from strokes in CSS px, typedSignature(name) from a typed name (drawn in a cursive system font into a PNG with transparency; the variable --vfjs-pdf-signature-font holds the font stack), await imageSignature(file) from a PNG / JPEG.
const sig = VibeFoxJSPdf.drawnSignature([[[0, 20], [20, 0], [40, 25], [60, 5], [80, 18]]], { color: '#1e3a8a' });
doc.page(0).addSignature(sig, 360, 720, { width: 120, date: true, author: 'Anna Berg' });
const typed = VibeFoxJSPdf.typedSignature('Anna Berg');
viewer.addSignature(typed, { page: 1, x: 60, y: 720, width: 140 });
In the viewer the signature tool (or openSignatureDialog()) opens a dialog with the tabs Draw, Type, Image and Saved, ink colors, "add the date" (signatureDate) and "save for next time": the event signatureSave gives the data; keeping it is up to your page, and the option signatures offers it again. placeSignature(data) lets the user place it with a click, addSignature(data, { page, x, y }) puts it at a place; events signatureCreate, signaturePlace.
Forms
Fillable PDF forms (AcroForm). Every field gets its appearance, so readers show it the same way, and its values can be filled, read, checked and exchanged — for fields made with the library and for the forms of opened files.
Creating fields
const form = new VibeFoxJSPdf.PdfDocument();
const fp = form.addPage();
fp.text('Name', { x: 50, y: 60 });
fp.addTextField('name', 150, 55, 200, { required: true, tooltip: 'Your full name' });
fp.addTextField('amount', 150, 85, 100, { format: { type: 'number', decimals: 2, min: 0 }, align: 'right' });
fp.addTextField('email', 150, 115, 200, { format: 'email' });
fp.addCheckbox('terms', 150, 145, { checked: false });
fp.addRadioButton('plan', 'basic', 150, 175);
fp.addRadioButton('plan', 'pro', 220, 175, { checked: true });
fp.addComboBox('country', 150, 205, 150, { options: ['Norway', 'Sweden', { value: 'FI', label: 'Finland' }], value: 'Norway' });
fp.addListBox('region', 150, 235, 150, { options: ['North', 'South', 'East'], multiple: true, height: 50 });
fp.addSignatureField('signature', 150, 300, 180, 50);
fp.addButton('reset', 150, 370, 80, 24, { label: 'Reset', action: 'reset' });
fp.addButton('send', 240, 370, 80, 24, { label: 'Send', action: { submit: 'https://example.com/form', format: 'xfdf' } });
Every field takes readOnly, required, noExport, tooltip (also the accessible name), borderColor and background. Text fields also take value, height, fontSize (0 = automatic), multiline, password, align, maxLen, font (a registered family: any script) and format: 'number', 'date', 'email', { type: 'number', decimals, min, max, decimalSeparator }, { type: 'date', pattern }, { type: 'pattern', pattern, message } (number and date formats are also applied by PDF readers while typing). Buttons only have safe actions: 'reset', 'print', { url }, { submit, format } — no JavaScript.
Filling and reading
form.setFieldValues({ name: 'Anna Berg', amount: '42', terms: true, plan: 'basic', country: 'FI', region: ['North', 'East'] });
console.log(form.getFieldValue('plan'), form.getFieldValues());
const check = form.validateForm(); // { valid, errors: [{ name, code, message }] }
const xfdf = form.exportFormData({ format: 'xfdf' }); // also 'json' (default) and 'fdf'
form.resetForm(['amount']);
form.importFormData(xfdf); // JSON, FDF or XFDF, detected
form.signField('signature', VibeFoxJSPdf.typedSignature('Anna Berg'), { date: true });
console.log(form.getFields().map((f) => `${f.name}: ${f.type}`), check.valid);
getFields() / getField(name) describe the fields ({ name, type, value, source, options, required, readOnly, format, page, widgets, … }). Values: text and combo — a string; list — a string or an array; check box — true / false; radio group — the export value or null. validateForm() checks required fields, formats, ranges and maximum lengths (codes 'required', 'format', 'range', 'maxLength'). Event fieldChange. flatten({ forms: true }) turns the fields into page content. Forms of opened files are filled the same way (names are the full names, parent.child) and saved as an incremental update.
Filling in the viewer
With forms: true the viewer puts real inputs over the fields: typing, check boxes, radio groups across pages, lists, a signature dialog for signature fields, the keyboard order of the page, ARIA names and error messages. Values go into the document at once. A submit button never sends anything: it validates the form and emits formSubmit with the values; formAction comes first and can stop the default (defaultPrevented = true).
const fv = VibeFoxJSPdf.createPdfViewer('#app2', { document: form, forms: true });
fv.on('fieldChange', (e) => console.log(e.name, e.value));
fv.on('formSubmit', (e) => { if (e.valid) console.log('send these values yourself:', e.values); });
const result = fv.validateForm(); // marks the invalid fields, focuses the first one
console.log(result.valid);
Redaction
Redaction removes content for good: the text, the vector graphics and the image pixels under the marked areas are taken out of the file, not painted over, and a box is drawn in their place. It works on documents of the library and on opened files (also encrypted ones), in the browser and in Node.
const pdf = await VibeFoxJSPdf.loadPdf(pdfBytes);
pdf.addRedaction(0, [50, 90, 200, 14]); // an area [x, y, w, h], page pt
const found = await pdf.redactText(['email', 'phone', 'iban'], { text: 'REMOVED' });
console.log(found.map((m) => m.match)); // review the marks before applying
pdf.removeRedaction(found[0].id);
const result = await pdf.applyRedactions({ metadata: true, bookmarks: false });
console.log(result.marks, result.removed.text, result.warnings);
const clean = await pdf.toBytes(); // always written as a new file now
- Marks first:
addRedaction(page, area, { color, text, textColor, label })(an area is[x, y, w, h], several{ rects }or the{ quads }of a selection),redactText(query, { pages, caseSensitive, wholeWord, padding })(a text, a regular expression or the patterns'email','phone'— international numbers with+, numbers with an area code in brackets, 10 digits and more, and local numbers such as555-1234; document numbers that start with a year (2026-001), dates and amounts with digit groups are not taken —,'card'— 13 to 19 digits with the Luhn check,'iban'— in groups of four or without spaces, with the mod 97 check;REDACTION_PATTERNSlists them). A match broken over two lines (a phone number, an IBAN, a card number) is one mark with a rectangle on each line, and itsmatchhas a space in place of the line break.getRedactions(),removeRedaction(id),clearRedactions(page). Marks live in memory: saving before applying them warns that the content is still in the file. applyRedactions(options)removes the characters whose center is in an area (the rest of the line keeps its place), the shapes and images inside (crossing shapes are clipped, crossing images get the pixels painted over), annotations, links and form fields touching an area, and draws the boxes (default black;textis an overlay text,textColordefault white). Options:color,text,textColor,ids,pages,metadata,xmp,bookmarks,attachments,javascript(remove those parts of the file too),keepMarks. The result counts what was removed.- From then on the document is always written as a new file (an incremental update would keep the old bytes). Signatures of a redacted file become invalid.
In the viewer, redaction: true adds the redaction bar: "Mark area" (drag boxes), "Mark selected text", a pattern / text / regular expression search with "Mark all", the list of marks (go to a mark, remove it) and "Apply redactions" with a confirmation. Marks are always shown. Methods setRedactionMode('area' | null), getRedactionMode, redactSelection(), redactSearch(query), applyRedactions(options), toggleRedactionList(open); events redactionModeChange, redactionAdd, redactionRemove, redactionApply.
Document comparison
await comparePdf(from, to, options) compares the text of two PDF documents (a PdfDocument, bytes, a Blob or a URL) word by word, in the browser and in Node. Line breaks, widths and font sizes do not count, so a reflowed text is no change; a word hyphenated at the end of a line is joined.
const cmp = await VibeFoxJSPdf.comparePdf(oldBytes, newBytes, { mode: 'document', ignoreCase: false });
console.log(cmp.summary.changes, cmp.summary.similarity);
for (const c of cmp.changes) console.log(c.type, JSON.stringify(c.old.text), '→', JSON.stringify(c.new.text), c.new.pages);
const report = cmp.toHtml({ title: 'Contract changes' }); // a standalone HTML report; cmp.toJSON() as data
- Options:
mode('document': the whole text, text moving to another page is no change;'page': page i with page i),ignoreCase,ignorePunctuation,joinHyphens(defaulttrue),password,visual(browser: also compare the pixels of the matched pages:trueor{ scale, threshold, images }),renderer,pdfjs. - The result:
summary(changes,inserted,deleted,equalwords,similarity, page and word counts),changes({ id, type: 'insert' | 'delete' | 'replace', old, new, words }, each side with itstext,pagesand boxesrects),pages(changes per page, the matching old page of every new page),visual(changed share and regions per page pair).
Comparison view
createPdfCompare(target, { from, to }) shows both documents side by side, scrolled together, with deletions marked on the old one, insertions on the new one and replacements outlined, a list of changes, previous / next buttons and JSON / HTML report downloads. layout: 'overlay' shows the new document alone with every change on it.
const cv = VibeFoxJSPdf.createPdfCompare('#app', { from: oldBytes, to: newBytes, layout: 'side', list: true });
cv.on('compareComplete', (e) => console.log(e.result.summary.changes));
cv.on('changeSelect', (e) => console.log(e.index, e.change.type));
await cv.compare();
cv.nextChange();
cv.setLayout('overlay');
Options from, to, layout, syncScroll, list, zoom, mode, ignoreCase, ignorePunctuation, visual, renderer, pdfjs, password; methods compare(), setDocuments(from, to), getResult(), getViewers(), setLayout(), setZoom(), goToChange(i), nextChange(), prevChange(), getReport('json' | 'html'), downloadReport(format); events compareComplete, compareError, changeSelect, layoutChange.
Digital signatures
Cryptographic signatures with certificates: signPdf(input, options) (or doc.sign(options)) signs a document and returns the signed PDF bytes; verifyPdf(input, options) checks every signature of a file. Signing uses WebCrypto (crypto.subtle: a secure page in the browser, Node 19 and newer); the library never makes network requests — time stamps and revocation data come through your callbacks.
Signing
// p12File: a .p12 / .pfx file chosen by the user; password: typed by the user
const signed = await VibeFoxJSPdf.signPdf(doc, {
pkcs12: { data: await p12File.arrayBuffer(), password },
reason: 'Approved',
location: 'Oslo',
page: 0,
rect: [360, 700, 190, 60], // visible signature box; no rect = invisible
appearance: { signature: VibeFoxJSPdf.typedSignature('Anna Berg') },
});
const report = await VibeFoxJSPdf.verifyPdf(signed, { trusted: rootPem });
console.log(report.status, report.signatures[0].signer.commonName);
- The key:
pkcs12(a .p12 / .pfx file and its password;loadPkcs12(bytes, password)returns{ key, certificate, chain }), orkey(a privateCryptoKey: RSA PKCS#1 v1.5, RSA-PSS, ECDSA P-256 / P-384 / P-521, Ed25519) withcertificateandchain(DER or PEM), or a signer object{ algorithm, sign(data) }for a hardware token or a signing server. format:'pades'(default, ETSI.CAdES.detached — PAdES B-B) or'pkcs7'(adbe.pkcs7.detached);hash: SHA-256 / 384 / 512.- Where:
field(an existing empty signature field, else the first empty one, else a new field),page+rect(visible) or no rect (invisible).appearance: a visual signature on the left, text lines on the right (default "Digitally signed by …", date, reason, location;textwith{name}{date}{reason}{location}),font,fontSize,color,background,border;localeof the default text. name,reason,location,contactInfo,date;certify: 1 | 2 | 3(a certification signature: 1 no changes allowed, 2 form filling and signing, 3 also comments; only as the first signature);lock(fields locked by this signature:true, names or{ action, fields }).timestamp: a callback that gets{ request, hash, hashAlgorithm, nonce }—requestis the RFC 3161 request (POST it to your time stamp authority withContent-Type: application/timestamp-query) — and returns the response bytes;revocation: { ocsps, crls }embeds revocation data.- Signing is an incremental update: earlier signatures stay valid. The document object is not changed; open the result with
loadPdfto go on working with the signed file.timestampPdf(input, { timestamp })adds a document time stamp.
Validation
verifyPdf(input, { trusted, certificates, revocation, password, time }) (or doc.verifySignatures()) checks the integrity of every signature, the signature value, the certificate path up to your trusted roots, the validity at the signing time (a verified time stamp, else the claimed time), revocation (embedded data, the document security store, your revocation callback) and the changes made after signing. The report: { status, valid, signatures, certified, revisions, warnings }; per signature status is 'valid', 'modified' (changed after signing, beyond what is allowed), 'invalid' or 'unknown' (the signer does not lead to a trusted root), with the signer, the time and its source, the time stamp, the certification level, locked fields and the list of later changes.
In the viewer a signed file gets a status line and a "Signatures" tab in the sidebar with the details of every signature. Give the trusted roots with the option signatureValidation: { trusted, certificates, revocation }; verifySignatures() checks again, getSignatureReport() returns the last report, event signaturesVerify.
Long-term validation
addValidationData(input, { revocation, trusted, certificates, timestamp }) (or doc.addValidationData() of an opened signed file) writes the certificates and the OCSP / CRL data of every signature into the document security store (PAdES B-LT); with timestamp a document time stamp follows (B-LTA). Your revocation(q) callback returns the OCSP response or CRL bytes for each certificate.
Encryption and permissions
setEncryption(options) (or the document option encrypt, or toBytes({ encrypt }) for one output) encrypts the saved file with the standard password security of PDF: method 'aes-256' (default) or 'aes-128', userPassword (needed to open; '' = opens without a prompt and the permissions apply), ownerPassword (full access; default: a random one), permissions (PDF_PERMISSIONS: print, modify, copy, annotate, fillForms, accessibility, assemble, printHighQuality; false = not allowed) and encryptMetadata.
doc.setEncryption({
userPassword: '', // opens without a password
ownerPassword: 'owner-secret',
permissions: { copy: false, modify: false, print: true },
});
console.log(doc.getEncryption().permissions);
const protectedBytes = await doc.toBytes();
const plain = await doc.toBytes({ encrypt: false }); // this output without encryption
An opened encrypted file keeps its encryption when saved. Changing or removing the encryption of a file that restricts anything needs its owner password (loadPdf(file, { password: owner })); otherwise toBytes() rejects with code: 'permission'. setEncryption(false) removes it, null goes back to the default.
PDF/A, PDF/UA and tagged PDF
Archive and accessibility standards for the files you write, plus checks and a conversion for any PDF.
pdfa:'2b','2u','2a','3b','3u','3a'(PDF/A-2 / -3),true= 2b, or{ part, conformance, strict }. The output gets the XMP metadata, an sRGB output intent and the fixes the standard needs; then it is checked. By default (strict)toBytes()rejects withcode: 'pdfa'and thereportwhen the file does not conform;strict: falsewrites it and emits awarning.pdfua: true: PDF/UA-1 (tagged, a language, the title shown, embedded fonts); problems found by the check arewarningevents, never errors.tagged: true: a structure tree without a conformance claim;lang: the document language.- Fonts: PDF/A and PDF/UA need embedded fonts. In these modes the standard families are drawn with your registered fonts (
standardFonts: { helvetica, times, courier, default }, else the document font, else the first registered family); without any registered font the save fails with an explanation.
const archive = new VibeFoxJSPdf.PdfDocument({
pdfa: '2u', pdfua: true, lang: 'en-US',
metadata: { title: 'Annual report 2026' },
font: { family: 'Noto Sans' },
});
await archive.loadFont('Noto Sans', 'fonts/NotoSans-Regular.ttf');
archive.text('Annual report', { size: 20, tag: 'H1' });
archive.text('Revenue grew by 12 %.'); // a P element
archive.image(logoPng, { width: 60, alt: 'Company logo' }); // a Figure with alternative text
archive.tag('L', () => {
archive.tag('LI', () => archive.text('First point'));
});
const bytes = await archive.toBytes();
console.log((await archive.checkPdfA()).conforms, (await archive.checkPdfUA()).conforms);
Structure
A tagged document tags its content automatically: each text() call is a paragraph (or the tag you give: 'H1' … 'H6', 'Caption', 'Code' …, with lang), images and SVG are figures (alt; alt: '' or artifact: true = decorative), tables are Table / TR / TH / TD, links, form fields and annotations get their elements, headers, footers, watermarks and table borders are artifacts. HTML to PDF maps headings, paragraphs, lists, tables, figures, links and lang attributes. For your own structure: beginTag(role, { alt, lang, actualText, title, scope, colSpan, rowSpan, key }) / endTag(), tag(role, options, fn), beginArtifact() / endArtifact(), setRoleMap({ Custom: 'P' }), setLanguage(); getStructure() returns the tree, STRUCT_ROLES lists the standard roles. Components of other VibeFox JS libraries added in a box are figures; a grid or an editor document added with addPageFrom keeps its table / heading structure.
Checks and conversion
const pdfaReport = await VibeFoxJSPdf.checkPdfA(pdfBytes, { part: 2, conformance: 'b' });
console.log(pdfaReport.conforms, pdfaReport.errors.map((e) => `${e.rule} ${e.message}`));
const uaReport = await VibeFoxJSPdf.checkPdfUA(pdfBytes);
const { bytes: archived, report } = await VibeFoxJSPdf.convertToPdfA(pdfBytes, { pdfa: '2b' });
console.log(report.conforms, report.fixed.length, report.failed);
checkPdfA checks the main rules of PDF/A-2 / -3 (file structure, output intent and colors, fonts embedded, transparency, annotations, actions, metadata, attachments, optional content; level a: tagging); checkPdfUA the machine-checkable rules of PDF/UA-1 (structure tree, every content tagged or an artifact, language, alternative texts, heading levels, tables, lists, annotations and fields in the tree). Errors name the clause of the standard. convertToPdfA (or doc.toPdfA()) converts any PDF and lists what was fixed and what could not be (fonts that are not embedded, CMYK colors with the sRGB output intent). These checks are built in and limited to the rules listed; they do not replace a full validator or a review by a person.
Templates and the designer
A template is JSON describing pages with elements and placeholders for data; renderTemplate(template, data, options) turns it into a PdfDocument in the browser or in Node. The designer (createPdfDesigner) edits templates visually over a live preview.
Templates
const template = {
name: 'Invoice',
page: { format: 'A4', margins: { top: 40, right: 40, bottom: 40, left: 40 } },
pages: [{ elements: [
{ type: 'heading', x: 40, y: 40, width: 380, height: 30, text: 'Invoice {{number}}', fontSize: 22 },
{ type: 'text', x: 40, y: 80, width: 300, height: 40, text: '{{customer.name}}\n{{customer.city}}' },
{ type: 'barcode', format: 'qr', x: 465, y: 40, width: 90, height: 90, value: 'INV-{{number}}' },
{ type: 'table', x: 40, y: 150, width: 515, height: 420, data: 'items', columns: [
{ header: 'Item', value: '{{name}}', width: 3 },
{ header: 'Qty', value: '{{qty}}', align: 'right' },
{ header: 'Price', value: '{{price | number:2}}', align: 'right', footer: '{{items | sum:qty*price | number:2}}' },
] },
{ type: 'text', x: 40, y: 590, width: 300, height: 20, text: '{{paid ? "PAID" : "DUE"}}', if: 'total > 0', bold: true },
{ type: 'textfield', name: 'comment', x: 40, y: 620, width: 300, height: 24, tooltip: 'Comment' },
] }],
};
const data = { number: 'A-17', paid: false, total: 1250, customer: { name: 'Anna Berg', city: 'Oslo' },
items: [{ name: 'Widget', qty: 2, price: 450 }, { name: 'Gadget', qty: 1, price: 350 }] };
const invoice = await VibeFoxJSPdf.renderTemplate(template, data, { locale: 'en-US' });
const flat = await VibeFoxJSPdf.renderTemplate(template, [data, data], { mode: 'flat' }); // two invoices, fields drawn
console.log(invoice.pageCount, flat.pageCount, VibeFoxJSPdf.templatePaths(template));
- Elements (
TEMPLATE_ELEMENTS):text,heading,image,line,rect,ellipse,table,barcode,repeat(a block repeated for every item: labels, cards), and the form fieldstextfield,checkbox,radio,combo,list,signature,button. Coordinates are pt from the top-left corner of the page. - Right to left:
dir('ltr'or'rtl') of the template is the default of its elements,dirof atext,headingortableelement overrides it (designer property "Text direction"). In a right-to-left elementalign: 'left'/'right'mean start / end (mirrored), and a table has its first column on the right. - Placeholders
{{path}}with expressions ({{qty * price}},{{paid ? "PAID" : "DUE"}}, comparisons,&&,||) and filters (TEMPLATE_FILTERS):number:2,currency:EUR,percent,date:dd.MM.yyyy,upper,lower,capitalize,trim,default:x,sum,avg,min,max,count,join,pad,yesno,first,last, and your own (filtersoption). Inside tables and repeated blocks: the fields of the row,$index,$number; also$page/$pages,$date,$root. Expressions are parsed by the library (noeval). - An element shows only when
ifis true; a table or a repeated block with more rows than its box continues on new pages (fromcontinueY), with the header row repeated and the footer row at the end;pages: 'first' | 'last' | 'all'chooses where the other elements of the page appear. A page withrepeatis made once per item of an array. A base PDF (base) is drawn under the pages. - Barcodes:
format'qr'(ecLevel),'datamatrix','code128','ean13','ean8','upca','code39','itf','itf14', drawn as vectors; QR and Data Matrix fill the box without the quiet zone (leave white space around them), linear codes print their text under the bars (showText). - Options of
renderTemplate:mode('form'fillable fields, default;'flat'fields drawn with their values),document(append to it),fonts,fallbackFonts,documentOptions(metadata,pdfa,tagged…),locale,currency,filters,resolveImage,base,password,onWarning. An array of records makes one document with all of them. A failing expression prints nothing and gives a warning. - Helpers:
normalizeTemplate(template)(every default filled in),fillTemplateText(text, { data }),templatePaths(template)(the data paths a template uses).
Designer
createPdfDesigner(target, { template, data }) is a WYSIWYG editor of templates: a palette of elements (drag them onto the page), the page drawn exactly as the PDF with the placeholders or with the preview data (preview), selection, moving and resizing with snapping to a grid and to guides, align and distribute, groups, layers, copy and paste, undo / redo, several pages, a base PDF, and a side panel (Properties, Layers, Data). The toolbar saves the template JSON and exports a fillable or a flat PDF.
const designer = VibeFoxJSPdf.createPdfDesigner('#app', { template, data, preview: true, zoom: 'fit' });
designer.on('templateChange', (e) => localStorage.setItem('invoice-template', JSON.stringify(e.template)));
const el = designer.addElement('text', { x: 40, y: 700, width: 300, height: 20, text: 'Thank you, {{customer.name}}!' });
designer.select(el.id);
designer.align('center', { to: 'page' });
const pdf = await designer.renderPdf({ data, mode: 'flat' });
console.log(pdf.pageCount, designer.getTemplate().pages[0].elements.length);
Options: template, data, preview, zoom (a number, 1 = 1 pt per CSS px, or 'fit'), palette (element types), grid, snap, fonts, fallbackFonts, dataLocale, readOnly, panel, renderer, pdfjs. Methods: getTemplate, setTemplate, renderPdf, downloadPdf, downloadTemplate, loadBasePdf, removeBasePdf, addElement, getElement, getElements, updateElement, removeElement, select, getSelection, selectAll, clearSelection, align, distribute, arrange, group, ungroup, copy, cut, paste, duplicate, undo, redo, canUndo, canRedo, getPage, goToPage, addPage, removePage, setPageFormat, getZoom, setZoom, zoomIn, zoomOut, getPreview, setPreview, showPanel, focusProperty, getWarnings, getState, setState. Events: templateChange, selectionChange, elementAdd, elementRemove, pageChange, zoomChange, previewChange, panelChange, historyChange, render, renderError. The framework wrappers keep template two-way bound.
Theming and styling
Themes
Every VibeFox JS component has the themes light (default), dark and high-contrast built into its CSS file. The optional vibefox-js-themes.css adds the theme pack: high-contrast-light, paper, paper-dark, glass, glass-dark, classic, classic-dark, ocean, ocean-dark, forest, forest-dark, sunset, sunset-dark, graphite, graphite-dark. The same file works for every VibeFox JS library.
VibeFoxJSPdf.setTheme('dark'); // the whole page
VibeFoxJSPdf.setTheme('ocean', '#sidebar'); // every component inside a container
viewer.setTheme('glass'); // one component (also: the theme option)
viewer.setTheme(null); // follow the page / container again
A component without its own theme follows the nearest container with a theme, then the page. After setTheme(name, container) the theme variables are set on the container itself too, so your CSS of the container can use them (#sidebar { background: var(--vfjs-bg); }). Your own theme: registerTheme(name, vars) with the theme variables (bg, fg, border, accent, accent-fg, muted, surface, radius, font, shadow, palette-0 … palette-9 and any other token); it applies at once to every component that uses it. getTheme() returns the page theme, themes lists the registered ones; the event themeChange reports a switch.
VibeFoxJSPdf.registerTheme('brand', { accent: '#e11d48', 'accent-fg': '#ffffff', radius: '10px' });
viewer.setTheme('brand');
CSS variables
Every color, size, spacing, font, radius, shadow and duration of VibeFox JS PDF is a CSS variable, so any setting is changed in one place. There are three levels:
- theme variables shared by all VibeFox JS components:
--vfjs-bg,--vfjs-fg,--vfjs-border,--vfjs-accent,--vfjs-accent-fg,--vfjs-muted,--vfjs-surface,--vfjs-radius,--vfjs-font,--vfjs-shadow,--vfjs-palette-0…--vfjs-palette-9; - design tokens: spacing
--vfjs-space-1…--vfjs-space-8, font sizes--vfjs-font-size,--vfjs-font-size-smand others, radii--vfjs-radius-sm…, status colors--vfjs-danger,--vfjs-success,--vfjs-warning,--vfjs-info, the scale--vfjs-size-unit, durations--vfjs-motion-duration, the focus ring--vfjs-focus-ring-colorand--vfjs-focus-ring-width; - variables of the library,
--vfjs-pdf-*, which default to the tokens above.
/* all VibeFox JS components of the page */
.vfjs { --vfjs-accent: #0f766e; --vfjs-radius: 4px; }
/* only this viewer */
#preview {
--vfjs-pdf-bg: #e2e8f0; /* workspace around the pages */
--vfjs-pdf-page-gap: 16px;
--vfjs-pdf-page-shadow: none;
--vfjs-pdf-toolbar-bg: #0f172a;
--vfjs-pdf-search-hit: rgb(250 204 21 / .4);
}
Main groups of the variables (all start with --vfjs-pdf-): frame and workspace (--vfjs-pdf-bg, --vfjs-pdf-fg, --vfjs-pdf-font, --vfjs-pdf-font-size, --vfjs-pdf-radius, --vfjs-pdf-density), toolbar and buttons (--vfjs-pdf-toolbar-bg, --vfjs-pdf-btn-hover-bg …), pages (--vfjs-pdf-page-bg — the paper color, --vfjs-pdf-page-shadow, --vfjs-pdf-page-gap, --vfjs-pdf-body-padding), sidebar and thumbnails (--vfjs-pdf-sidebar-width, --vfjs-pdf-thumb-width …; the tabs: --vfjs-pdf-tab-icon-size, --vfjs-pdf-tab-gap, --vfjs-pdf-tab-label-display — none by default, inline shows the names next to the icons), text selection and search (--vfjs-pdf-selection, --vfjs-pdf-search-hit, --vfjs-pdf-search-current), boxes over links and fields (--vfjs-pdf-link-highlight, --vfjs-pdf-field-highlight, transparent by default), annotations (--vfjs-pdf-annot-highlight, --vfjs-pdf-annot-color-0 … --vfjs-pdf-annot-color-7, --vfjs-pdf-stamp-positive …), signature dialog (--vfjs-pdf-sign-color-0 …, --vfjs-pdf-signature-font — the system handwriting fonts of typed signatures, no font files), form fields (--vfjs-pdf-field-bg, --vfjs-pdf-field-focus-bg, --vfjs-pdf-field-invalid), redaction (--vfjs-pdf-redact-mark-bg …), signature status (--vfjs-pdf-sig-valid …), comparison (--vfjs-pdf-diff-ins, --vfjs-pdf-diff-del, --vfjs-pdf-compare-list-width), designer (--vfjs-pdf-designer-bg, --vfjs-pdf-designer-grid-color, --vfjs-pdf-designer-selected, --vfjs-pdf-designer-color-0 …). The pages are drawn again when a variable they use changes. The colors written into a PDF file (annotations, template colors) are stored as plain colors, independent of the theme.
From JavaScript: set a variable on the element of the component (viewer.el.style.setProperty('--vfjs-pdf-page-gap', '24px')); className adds your own classes.
Where to set them: on :root, on any container of your page (#checkout { --vfjs-accent: #0f766e; }), on the element of the component, or in a theme (registerTheme). The closest value wins; a component with its own theme (the option theme or component.setTheme(name)) keeps the theme variables of that theme even inside a container that sets them. A container inside another component (a form inside a dialog or a card) passes the variables of the library to the components in it as well. Only the shared design tokens (--vfjs-space, --vfjs-danger, --vfjs-selected-bg …) do not pass there: set them on a container outside the outer component or on the nested components themselves (#form .vfjs { … }). Popups, menus and dialogs placed in <body> take the values set on the page (:root), not those of the container of their component.
Default values: the theme variables are registered with @property (their initial value is the light theme), so they have a value on every element of the page. The variables of the library (--vfjs-pdf-*) keep their defaults inside the stylesheet, at the place where they are used, so a variable that you did not set has no value on your elements:
- in your own CSS that uses a variable of the library, give it a fallback as the library does:
var(--vfjs-pdf-bg, var(--vfjs-bg)), or use a theme variable directly; - from JavaScript, read the current value with
cssVar(element, '--vfjs-pdf-page-gap')(exported by the library; it also returns the default value the component computes);getComputedStyle(element).getPropertyValue()can return an empty string for a variable of the library that nobody set.
/* your own element in the colors of the component */
.my-summary { background: var(--vfjs-pdf-bg, var(--vfjs-bg)); color: var(--vfjs-fg); }
const el = document.querySelector('#orders');
console.log(VibeFoxJSPdf.cssVar(el, '--vfjs-pdf-page-gap')); // the value in use (also a default)
console.log(getComputedStyle(el).getPropertyValue('--vfjs-pdf-page-gap')); // can be '' unless you set it
If the CSS file of the library comes from another origin without CORS (a <link> without the crossorigin attribute), the browser does not let scripts read the stylesheet, and cssVar() returns an empty string for a variable without a value on the root of the component. From your own origin, or with that attribute, it works.
--vfjs-pdf-zoom (the current zoom of a page) and --vfjs-pdf-designer-swatch (the color of one swatch) have no value of their own: the library sets them on those elements, so there is nothing to change. --vfjs-pdf-density sets the density of the viewer spacing: --vfjs-pdf-space (the spacing step) is --vfjs-space-unit × --vfjs-pdf-density, and the paddings and gaps of the viewer are multiples of it.
The stylesheets are written with native CSS nesting; nothing changes for including them, and your own CSS can be written in any form.
Ready-made styles
The viewer option style (the prop variant in the framework wrappers) picks a ready-made look; every style works with every theme and density.
| Style | Look |
|---|---|
'classic' | Grey workspace, raised square pages. |
'dark' | Dark workspace and toolbar whatever the theme. |
'minimal' | No frame, a transparent toolbar, outlined flat pages. |
'compact' | Smaller controls, text and paddings. |
'paper' | Warm workspace, tinted paper. |
viewer.setStyle('dark'); // or the option style: 'dark'
viewer.getStyle(); // 'dark'
viewer.setStyle(null); // the default look
PDF_VIEWER_STYLES lists the names; setStyle emits styleChange. A style is the class vfjs-pdf-style-<name> on the viewer or any container; any other name uses your own CSS for that class.
Density and size
Set data-vfjs-density="compact", "normal" or "comfortable" on the page or on any container: heights and paddings of every VibeFox JS component inside follow. --vfjs-size-unit (default 1px) scales all sizes of a component at once, for example #orders { --vfjs-size-unit: 1.25px; }. Sizes you give as numbers in options are pixels and are not scaled.
Default height: when the element of the component has no height of its own, it gets the class vfjs-auto-height and a default height from the variable --vfjs-pdf-min-height (400 px × --vfjs-size-unit; the comparison view: --vfjs-pdf-compare-min-height, also 400 px); the pages scroll inside and only the pages in view are drawn. An element with a height of its own (height, only a min-height, a flex item or a CSS Grid item, height: 100% of a parent with a height, absolute insets) gets the class vfjs-fit and is filled exactly, also when it is smaller; the content never makes it taller. With the variable at 0 (class vfjs-content-height) the viewer is as high as all its pages, without scrolling of its own. The designer is different: without a height it is at least --vfjs-pdf-designer-min-height (520 px) and grows with its content; an explicit height is kept exactly.
Your own CSS
All library rules are inside the cascade layer @layer vfjs, so your own CSS always wins without !important. The class names of VibeFox JS PDF start with vfjs-pdf- (state classes too, for example vfjs-pdf-is-selected), so other CSS frameworks on the page do not restyle it.
.vfjs-pdf-toolbar { border-block-end: 2px solid #0f766e; }
.vfjs-pdf-thumb.vfjs-pdf-is-current { outline-color: #0f766e; }
The library ships no font files. It uses the system font stacks of the tokens --vfjs-font, --vfjs-font-mono and --vfjs-font-serif; set them to your own fonts if you want. Animations follow prefers-reduced-motion, and colors follow forced-colors mode (Windows high contrast).
Localization and RTL
Languages
VibeFox JS PDF comes with 14 interface languages. English (en) is built into the library file; each of the others is a language file of its own (dist/locales/vibefox-js-pdf.<lang>.js in the package), and a page loads only the ones it uses: Russian (ru), Spanish (es), German (de), French (fr), Italian (it), Portuguese (Brazilian) (pt), Ukrainian (uk), Turkish (tr), Chinese (Simplified) (zh), Japanese (ja), Korean (ko), Hindi (hi) and Arabic (ar). The locale option sets the language of one component; setLocale(lang) sets the default language of the page, which every component without its own locale follows (it re-renders on a change).
VibeFoxJSPdf.setLocale('ru'); // page default
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: doc, locale: 'en' }); // this viewer only
viewer.setOptions({ locale: 'de' });
The example above needs the files of the languages it uses. With script tags, load a language file after the library. The order matters: loaded first, the file adds no language and writes a warning to the console.
<link rel="stylesheet" href="vibefox-js-pdf.css">
<script src="vibefox-js-pdf.global.min.js"></script>
<script src="locales/vibefox-js-pdf.ru.js"></script>
With npm or a bundler, import the language after the library. Without npm, an ES module page imports ./locales/vibefox-js-pdf.ru.esm.js, which registers the language in vibefox-js-pdf.esm.js.
import { createPdfViewer } from '@vibefox/js-pdf';
import '@vibefox/js-pdf/locales/ru';
The .esm.js language file does not fit the minified build @vibefox/js-pdf/min (it would load a second copy of the library). There, use the .json file:
import { createPdfViewer, addLocale } from '@vibefox/js-pdf/min';
import ru from '@vibefox/js-pdf/locales/ru.json';
addLocale('ru', ru);
Without its file, locale: 'ru' shows English and writes one warning to the console.
Language codes: uk, ko, zh and pt are the real codes; ua and kr also work, as aliases of uk and ko. For each string the library tries the exact code, then the alias, the base language (pt-BR → pt, zh-CN → zh), English, and finally the key itself. normalizeLocale(code) returns the real code of an alias.
A language does not set the direction: with locale: 'ar', also set rtl: true or dir="rtl" on the container.
Adding a language
addLocale(lang, dictionary) adds strings to a language (and creates it): a language of your own, or your own wording over a language file. A missing key follows the chain above, so a partial dictionary works; addLocale('ua', …) fills uk. Add the dictionary before the components that use it are created, or switch the locale afterwards.
VibeFoxJSPdf.addLocale('de', {
pdfZoomIn: 'Vergrößern',
pdfZoomOut: 'Verkleinern',
pdfDownload: 'PDF herunterladen',
});
The keys of VibeFox JS PDF are camel-case names with the prefix pdf (for example pdfZoomIn, pdfSearch, pdfAnnot_highlight, pdfTool_ink, pdfRedactApply, pdfCompareNext, pdfDesignerAddPage): the toolbar, the search bar, the sidebar, the annotation, signature, form, redaction and signature-status texts, the comparison view and the designer, with the screen reader texts. The language files list every key (locales/vibefox-js-pdf.ru.json); the English texts are in the readable file vibefox-js-pdf.esm.js. Placeholders in braces, such as {page}, are filled in by the library. t(key, params) translates a key in the page locale, viewer.t(key) in the viewer's locale; getLocale() returns the page locale, onLocaleChange(fn) reports changes.
Plural forms: a text with a number has the keys <key>.zero, .one, .two, .few, .many and .other (the categories of Intl.PluralRules); .other is the fallback, so your dictionary can give only that form. {count} and {n} are filled in. tPlural(key, count, params, lang) picks the form; the method viewer.tPlural(key, count, params) does it in the locale of the component.
VibeFoxJSPdf.addLocale('de', {
'pdfRedactConfirm.one': 'Inhalt unter {count} Markierung entfernen?',
'pdfRedactConfirm.other': 'Inhalt unter {count} Markierungen entfernen?',
});
VibeFoxJSPdf.tPlural('pdfRedactConfirm', 5, {}, 'de'); // 'Inhalt unter 5 Markierungen entfernen?'
The language of the component does not change the PDF files: texts you put into a document are yours. Some generated texts follow a locale of their own: the labels of ready-made stamps (lang of the stamp: the key pdfStamp_<key> of that language, else English), the default text of a visible digital signature (locale of signPdf), {date} of HTML headers and footers (locale), and the number, currency and date filters of templates (locale of renderTemplate, dataLocale of the designer).
Right-to-left
The option rtl: true lays the component out right-to-left (dir="rtl" on its element); rtl: false forces left-to-right; without it the component follows the page or its container (<html dir="rtl">). The arrow keys follow the reading order. isRtl(element) tells the direction of an element.
In VibeFox JS PDF the toolbar, the sidebar, the panels and the dialogs follow the direction, the previous / next page buttons point the reading direction and the bookmark tree keys follow the reading order; the pages and the text layer keep the geometry of the PDF. Inside PDF documents, right-to-left text (Arabic, Hebrew) is written right to left with the Unicode bidirectional algorithm and shaped by the font (see Fonts → Right-to-left and complex scripts): the option dir of texts, tables, documents and templates, align: 'start' / 'end', and dir / direction in HTML. The text layer, search and copying of the viewer give right-to-left text in reading order.
Accessibility
The viewer is a labelled region with a toolbar (one tab stop, arrow keys inside), pages as labelled groups, a selectable text layer that screen readers can read, and live announcements of search results, page edits and form errors. Annotations are a list of focusable items with their type, author and text; form fields are real inputs with their names, required and invalid states; the designer, the comparison view, the sidebar, the signature and stamp dialogs are fully usable with the keyboard. Focus is visible (the focus ring is the CSS variables --vfjs-focus-ring-color, --vfjs-focus-ring-width, --vfjs-focus-ring-offset, --vfjs-focus-ring-style); dialogs keep the focus inside and give it back when they close. The high-contrast and high-contrast-light themes, forced-colors mode and prefers-reduced-motion are supported. For accessible PDF files see PDF/A, PDF/UA and tagged PDF.
Keyboard
On macOS, Cmd works where Ctrl is listed.
Viewer
| Keys | Action |
|---|---|
| Ctrl+F | Open the search bar. |
| Enter, Shift+Enter (search bar) | Next / previous match. |
| F3, Shift+F3, Ctrl+G | Next / previous match. |
| Esc | Close the search bar, end the area marking of redaction, cancel placing. |
| Ctrl + / Ctrl − / Ctrl+0 | Zoom in / out / 100 %. |
| Home, End (pages) | First / last page. |
| n, j / p, k (pages) | Next / previous page. |
| PageDown, PageUp, →, ← (single layout) | Next / previous page. |
| r, Shift+R | Rotate the view clockwise / counter-clockwise. |
| ↑ ↓ Home End Enter Space (thumbnails) | Move, open the page. |
| ↑ ↓ ← → Home End Enter (bookmarks) | Move, expand / collapse, open. |
Annotations and page editing
| Keys | Action |
|---|---|
| Tab | To the next annotation of the page. |
| Arrows, Shift+arrows, Alt+arrows | Move the annotation (×10), resize it. |
| Delete, Backspace | Delete the selected annotation / the selected pages. |
| Enter | Edit a note or a text box; make a markup annotation of the selected text. |
| Ctrl+Enter | Done (text box, reply of a note). |
| Enter, double click, Backspace, Esc (polyline / polygon) | End, end, remove the last point, cancel. |
| Enter (placing a stamp or a signature) | Put it in the middle of the current page. |
| Ctrl+Z, Ctrl+Y, Ctrl+Shift+Z | Undo / redo (annotations and page edits). |
| Space, Shift+↑ ↓ Home End, Ctrl+A (thumbnails, page editing) | Select pages. |
| R, Shift+R, Alt+↑ ↓ (thumbnails, page editing) | Rotate, move the pages. |
Designer and comparison view
| Keys | Action |
|---|---|
| Arrows, Shift+arrows, Alt+arrows (element) | Move by 1 pt / one grid step, resize. |
| Space, Delete, Enter / F2, Esc (element) | Toggle the selection, delete, edit the properties, leave. |
| Ctrl+A, Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D | Select all, copy, cut, paste, duplicate. |
| Ctrl+G, Ctrl+Shift+G | Group / ungroup. |
| Ctrl+], Ctrl+[ (Shift: to the front / back) | Forward / backward in the z-order. |
| Ctrl+Z, Ctrl+Y, Ctrl + / − / 0 | Undo / redo, zoom. |
| Alt+PageDown, Alt+PageUp (comparison view) | Next / previous change. |
| ↑ ↓ Home End Enter (list of changes) | Move, show the change. |
Screen readers
Roles: the viewer region ("PDF viewer"), toolbar with aria-labels and aria-pressed toggles, the search bar search with a live count, pages group ("Page n"; the canvases are hidden from screen readers), thumbnails listbox (aria-multiselectable with page editing, aria-current="page"), bookmarks tree, sidebar tablist, annotations listbox / option, dialogs dialog with aria-modal, the notice and signature lines status. Form fields have aria-label (the tooltip or the name), aria-required, aria-readonly and aria-invalid.
The library also exports the helpers it uses itself: announce(message), trapFocus, rovingFocus, setAria, prefersReducedMotion() and others (see API reference).
Using with other VibeFox JS libraries
VibeFox JS PDF works on its own. Every VibeFox JS library is a separate file with its own copy of the shared core, and several libraries on one page work together without conflicts: one global variable per library (VibeFoxJSPdf, VibeFoxJSCharts, …), class names with the library prefix, one page theme, the same events.
Connecting components with link()
link(source, event, target, method, transform) calls a method of one component whenever another emits an event; it returns a function that removes the link. connect(source, event, handler) subscribes and returns an unsubscribe function. bus is a page-wide event channel shared by all VibeFox JS libraries on the page.
// two viewers turn their pages together
const second = VibeFoxJSPdf.createPdfViewer('#app2', { document: doc });
const unlink = VibeFoxJSPdf.link(viewer, 'pageChange', second, 'goToPage', (e) => e.page);
VibeFoxJSPdf.bus.emit('docs:saved', { at: Date.now() }); // any library can listen: VibeFoxJSGrid.bus.on('docs:saved', fn)
What uses another library when it is on the page
- Components of other VibeFox JS libraries in a PDF:
addComponent(),addComponents()andaddPageFrom()take a chart, grid, diagram, Gantt chart, trading chart or editor that is on the page and draw it into your document (see VibeFox JS components in a PDF). VibeFox JS PDF works on its own; these calls need only the component you pass. - The other way round: if VibeFox JS PDF is also on the page, the other VibeFox JS libraries find it and use it for their PDF features (for example
toPdfDocument()andpreviewPDF()of VibeFox JS Grid or VibeFox JS Diagram): they build aPdfDocumentof this library and show it in the VibeFox JS PDF viewer. - Everything else of VibeFox JS PDF — documents, opening files, the viewer, signatures, templates — needs no other library.
API reference
Exports
Classes and factories: PdfDocument, PdfPage, createPdfViewer, VibeFoxJSPdfViewer, createPdfDesigner, VibeFoxJSPdfDesigner, createPdfCompare, VibeFoxJSPdfCompare, PdfComparison.
Functions: loadPdf, htmlToPdf, renderTemplate, normalizeTemplate, fillTemplateText, templatePaths, comparePdf, signPdf, timestampPdf, verifyPdf, loadPkcs12, addValidationData, checkPdfA, checkPdfUA, convertToPdfA, srgbProfile, renderPageToCanvas, renderPageLite, layersLite, useLiteWorker, startLiteWorker (internal: the worker side), liteCacheLimit, usePdfJs, drawnSignature, typedSignature, imageSignature, parsePdf, parseJpeg, resolveFont, measureText, pickEncoding, resolvePageSize, pageFormatName, parseColor, enableComplexScripts (and the flag complexScripts, see Right-to-left and complex scripts).
Constants: FORMATS, PDF_VIEWER_STYLES, ANNOTATION_TYPES, PDF_ANNOTATION_TOOLS, PDF_STAMPS, PDF_PERMISSIONS, REDACTION_PATTERNS, STRUCT_ROLES, TEMPLATE_ELEMENTS, TEMPLATE_FILTERS, VERSION.
Shared core (the same in every VibeFox JS library): setTheme, getTheme, registerTheme, themes, tokens, componentTokens, densities, cssVar, cssColor, cssLength, observeTokens, setLocale, getLocale, addLocale, normalizeLocale, t, tPlural, withLocale, onLocaleChange, link, connect, bus, Emitter, VibeFoxJSComponent, factory, toCSV, downloadFile, downloadCanvasPNG, createVectorImage, loadVectorImage, announce, trapFocus, rovingFocus, getFocusable, focusFirst, saveFocus, setAria, ensureId, addAriaRef, removeAriaRef, isRtl, mirrorArrow, prefersReducedMotion, prefersHighContrast, motionDuration, onPreferenceChange, injectStyles, ensureBaseStyles, formatNumber, formatDate, escapeHtml, createEl, deepMerge, isPlainObject, getPath, setPath, uid, clamp, debounce, throttle.
PdfDocument options
| Option | Type | Default | Description |
|---|---|---|---|
format | name or [w, h] | 'A4' | Page size of new pages (A0–A10, B0–B10, C0–C10, DL, Letter, Legal, Tabloid, Ledger, Executive, Statement; an unknown name throws code: 'page-format'). |
orientation | 'portrait' or 'landscape' | 'portrait' | Orientation. |
margins | { top, right, bottom, left } | { top: 56, right: 50, bottom: 56, left: 50 } | Margins, pt. |
metadata | object | {} | title, author, subject, keywords, creator, producer, creationDate. |
compress | boolean or 'auto' | 'auto' | Compress the content streams. |
font | object | { family: 'helvetica', size: 12, color: '#111111', lineHeight: 1.35, kerning: true, ligatures: true } | Default font of the flow. |
dir | 'ltr', 'rtl' or 'auto' | 'auto' | Direction of text, tables and templates. |
fonts | array | — | Font files to register: [{ family, data, weight, style }]. |
fallbackFonts | string[] | [] | Fallback families. |
header, footer | string or object | null | Header / footer line. |
watermark | string or object | null | Watermark of every page. |
encrypt | object or false | — | Encryption when saved. |
pdfa, pdfua, tagged, lang, standardFonts | see PDF/A, PDF/UA and tagged PDF | — | Conformance of the saved file. |
loadPdf takes the same options plus password and onWarning; format of new pages defaults to the size of the first page of the file.
PdfDocument methods
| Method | Returns | Description |
|---|---|---|
addPage, insertPage, page(i), removePage, movePage, rotatePage, copyPages, extractPages, split | page / this / documents | Pages (properties pages, pageCount, currentPage, cursor, outline, metadata, options, sourceInfo). |
text, image, svg, table, setCursorY, moveDown, ensureSpace | this / table result / page | Flow. |
addHtml(html, options) | Promise<{ pages, height, warnings }> | HTML into the flow. |
addComponent, addComponents, addPageFrom | Promise | VibeFox JS components as vectors. |
addImage(src), getImage(id) | id / image | Image registry. |
registerFont, loadFont, setFallbackFonts, getFonts, hasFont | this / Promise / faces / boolean | Fonts. |
setHeader, setFooter, setWatermark, setMetadata, addBookmark | this / bookmark | Decorations and navigation. |
toBytes, save, toDataURL, toBlobURL | Promise | Output. |
toJSON(options), PdfDocument.fromJSON(json, options), PdfDocument.merge(...docs) | object / document | Snapshots and merging. |
getRenderOps(pageIndex) | ops | The final drawing commands of a page. |
addAnnotation, getAnnotations, getAnnotation, updateAnnotation, removeAnnotation, exportAnnotations, importAnnotations, flatten | annotation / data / this | Annotations. |
getFields, getField, getFieldValue, setFieldValue, getFieldValues, setFieldValues, resetForm, validateForm, exportFormData, importFormData, signField | fields / values / result | Forms. |
addRedaction, getRedactions, removeRedaction, clearRedactions, redactText, applyRedactions | mark / Promise | Redaction. |
searchText, extractText | Promise | Text. |
sign, addTimestamp, verifySignatures, addValidationData | Promise | Digital signatures. |
setEncryption, getEncryption | this / info | Encryption. |
setConformance, getConformance, beginTag, endTag, tag, beginArtifact, endArtifact, setRoleMap, setLanguage, getLanguage, getStructure, isTagged, toPdfA, checkPdfA, checkPdfUA | this / value / Promise | PDF/A, PDF/UA, tagging. |
on, once, off, emit | this | Events. |
PdfPage methods
| Method | Returns | Description |
|---|---|---|
text(text, options), measureText(text, options) | box / number | Placed text. |
drawLine, drawRect, drawEllipse, drawCircle, drawPolygon, drawPath | this | Shapes. |
drawImage, drawSvg, drawPage | size / box | Images, SVG, pages of documents. |
beginGroup, endGroup, group | this | Transform, clip, opacity. |
link(x, y, w, h, target) | this | Link. |
addTextField, addCheckbox, addRadioButton, addComboBox, addListBox, addSignatureField, addButton | field | Form fields. |
addAnnotation, getAnnotations, updateAnnotation, removeAnnotation, addSignature | annotation | Annotations of the page. |
setRotation(angle) | this | Page rotation (properties width, height, margins, contentWidth, contentHeight, index, rotation, isLoaded). |
PdfDocument events
| Event | Payload | Description |
|---|---|---|
change | { type, page, base } | Any change (the viewer follows it). |
pageAdd, pageRemove | { page, index } | A page added / removed. |
save | { filename, size } | Saved with save(). |
warning | { source, messages } | Unsupported SVG / HTML, saving a signed file, PDF/A or PDF/UA problems, unapplied redaction marks. |
annotationAdd, annotationChange, annotationRemove | { annotation, previous, page } | Annotations. |
flatten | { annotations, forms } | Flattened. |
fieldChange | { name, value, previous, reset, signature } | A field value changed. |
redactionAdd, redactionRemove, redactionApply | { redaction } / result | Redaction. |
Viewer options
Also every VibeFox JS component accepts theme, locale, rtl and on (see Core concepts).
| Option | Type | Default | Description |
|---|---|---|---|
document | PdfDocument or null | null | The document shown. |
page | number | 1 | Current page (1-based); opened at creation, setOptions({ page }) turns to it. |
zoom, minZoom, maxZoom | number | 1, 0.25, 4 | Zoom. |
toolbar | boolean | true | Show the toolbar. |
filename | string | 'document.pdf' | Name of the downloaded file. |
style | string or null | null | Ready-made look. |
layout | 'continuous' or 'single' | 'continuous' | All pages in one scroll / one page at a time. |
rotation | 0, 90, 180, 270 | 0 | View rotation. |
renderer | 'auto', 'lite', 'pdfjs' | 'auto' | What draws the original content of opened files. |
pdfjs | namespace, URL, adapter or false | null | pdf.js for this viewer. |
sidebar | 'thumbnails', 'outline', 'layers', 'signatures' or null | null | Open sidebar view. |
textLayer | boolean | true | Selectable text over the pages. |
annotations | boolean | false | Annotation toolbar and editing. |
annotationTools | string[] or null | null | Tools of the annotation toolbar. |
author | string | '' | Author of new annotations. |
signatures | array | [] | Saved signatures offered in the signature dialog. |
signatureDate | boolean | false | "Add the date" checked in the dialog. |
pageEditing | boolean | false | Page tools in the thumbnail panel. |
forms | boolean | false | Fill in form fields. |
redaction | boolean | false | Redaction tools. |
signatureValidation | object or null | null | Trusted roots, certificates and revocation callback for signed files. |
Viewer events
| Event | Payload | Description |
|---|---|---|
ready, optionsChange, themeChange, destroy | see Core concepts | Common events. |
pageChange | { page, pages } | Current page changed. |
zoomChange, rotationChange, styleChange | { zoom }, { rotation }, { style, previous } | View changed. |
documentChange | { document } | Another document shown. |
renderComplete, renderError | { page, original }, { page, error } | A page drawn / failed. |
searchChange, sidebarChange, layersChange | search state, { view }, { layers } | Search, sidebar, layers. |
toolChange, annotationSelect, historyChange, stampPlace, annotationAdd, annotationChange, annotationRemove | { tool }, { annotation }, { canUndo, canRedo } … | Annotations. |
signatureCreate, signatureSave, signaturePlace | { signature }, { annotation } | Visual signatures. |
pageEdit, pageSelectionChange, pageInsertError | { action, pages, angle, from }, { pages }, { error, file } | Page editing. |
fieldChange, fieldError, fieldSign, formAction, formSubmit, formValidate | field / form payloads | Forms. |
redactionModeChange, redactionAdd, redactionRemove, redactionApply | { mode }, { redaction }, result | Redaction. |
signaturesVerify | { report } | Signatures of the shown file checked. |
printProgress, print | { page, done, total }, { pages, total, window } | Printing: a page prepared / the dialog opens next. |
Viewer methods
| Method | Returns | Description |
|---|---|---|
setOptions, getState, setState, setTheme, on, once, off, t, destroy | — | Common methods (see Core concepts). |
setDocument(doc, { page }), getDocument, refresh, download | this / document / Promise | Document. |
print(options), cancelPrint(), canPrint() | Promise / this / boolean | Printing. |
goToPage, nextPage, prevPage, setZoom, zoomIn, zoomOut, fitWidth, fitPage, rotate, setRotation, getRotation | this / number | Navigation and view. |
setStyle, getStyle | this / string | Look. |
search, searchNext, searchPrev, clearSearch, getSearch, showSearch, hideSearch, getPageText | Promise / state / this | Search. |
showSidebar, hideSidebar, toggleSidebar, getLayers, setLayerVisible | this / layers | Sidebar and layers. |
setTool, getTool, selectAnnotation, getSelectedAnnotation, deleteAnnotation, editAnnotation, placeStamp, undo, redo, canUndo, canRedo | this / annotation / boolean | Annotations. |
openSignatureDialog, placeSignature, addSignature | this / annotation | Visual signatures. |
selectPages, getSelectedPages, rotatePages, removePages, movePages, insertPages | this / pages / Promise | Page editing. |
validateForm, signField | result / this | Forms. |
setRedactionMode, getRedactionMode, redactSelection, redactSearch, applyRedactions, toggleRedactionList | this / marks / Promise | Redaction. |
verifySignatures, getSignatureReport | Promise / report | Digital signatures. |
The options, events and methods of the designer and of the comparison view are listed in their sections (Templates and the designer, Document comparison). The TypeScript declarations (vibefox-js-pdf.d.ts) describe every option, payload and return type in detail: PdfDocumentOptions, PdfViewerOptions, PdfViewerEvents, PdfAnnotation, PdfSignOptions, PdfSignaturesReport, PdfTemplate, PdfDesignerOptions, PdfCompareViewOptions and others.
Troubleshooting
No styles
Link vibefox-js-pdf.css next to the script. Without it the component works but is unstyled, and the console shows one warning "VibeFox JS stylesheet is not loaded". In a bundler, import @vibefox/js-pdf/css. The framework wrappers do not add the CSS for you.
My CSS does not apply, or a page CSS framework changes the component
Your rules win over the library rules without !important because the library CSS is in @layer vfjs. If they still do not apply, check the class names: state classes have the library prefix (vfjs-pdf-is-selected, not is-selected). The library never uses generic class names, so page CSS frameworks do not change it.
ES modules do not load from disk
Browsers load <script type="module"> only over http(s). Use a local web server, or use vibefox-js-pdf.global.js, which also works from file://.
Content Security Policy
The library does not use eval or inline scripts and loads nothing from the network. It sets inline styles on its elements (sizes and positions), so a policy with style-src must allow them ('unsafe-inline' for style attributes). The renderer of opened PDF files starts its Web Worker from a Blob URL that loads the library file (worker-src blob:); without that permission it draws in the main thread. Printing puts the page images into a hidden frame as blob: URLs (img-src blob:). A URL you pass (a file, an image, a font) is loaded with fetch, so connect-src must allow it.
Characters are printed as "?" or the text is not in my font
The library ships no fonts. The standard PDF fonts have Latin and Cyrillic characters (and Greek letters, math signs and dingbats in 'symbol' / 'zapfdingbats'); other characters (CJK, Arabic, Hebrew, Devanagari, ₽ …) need a font file of yours: register a .ttf, .otf or .woff with registerFont / loadFont (or the option fonts) and use its family, or add it with setFallbackFonts. WOFF2 files are not read: convert them. In HTML, @font-face with TTF / OTF / WOFF files is registered for you. Arabic written in separate letters or Hebrew in reversed order means the complex-script engine is not in your own build: call enableComplexScripts().
Saving as PDF/A fails
PDF/A needs embedded fonts: the standard fonts cannot be embedded. Register a font file before adding content; it is used for the standard families too. The error has a report with the failed clauses; strict: false writes the file anyway, toPdfA() returns the file and the report.
Signing or opening an AES-256 file fails with a message about crypto.subtle
WebCrypto is available only on secure pages (https or localhost) and in Node 19 and newer.
Nothing is shown or the viewer has the wrong height
The target element must exist when createPdfViewer runs (a selector that finds nothing throws an error). The viewer fills its element: give the element a height (CSS or an inline style), or let a flex or grid layout give it one; without either, the viewer is 400 px high (--vfjs-pdf-min-height). With --vfjs-pdf-min-height: 0 it is as high as all its pages, and every page is drawn — avoid that for long documents.
Pages of an opened file show only the added drawing
The option renderer: 'pdfjs' without a connected pdf.js shows only what was drawn with the library (a notice line says so). Use the default 'auto' or 'lite'.
Saving an opened file throws "permission"
Changing or removing the encryption of a restricted file needs its owner password: open it with loadPdf(file, { password: owner }).
Copy and paste of text do not work
The browser gives clipboard access only on secure pages (https or localhost) and after a user action. Text of the standard fonts and of your embedded fonts can be copied; text drawn as pictures (scans) has nothing to copy.
Limitations
- Fonts: no vertical text; shaping has its own rules for Arabic, Hebrew and Devanagari only — other Indic scripts (Bengali, Tamil …), Thai, Khmer, Myanmar and Mongolian get the general shaping of the font, without their reordering rules; justified text is not stretched with kashida; AAT and Graphite tables of a font are not used; variable fonts give their default instance, no color emoji, no synthetic bold / italic, no WOFF2.
- SVG: masks, filters, patterns,
textPath,<foreignObject>, GIF / WebP images and repeated / reflected gradients are not drawn (repeated gradients are padded). - HTML to PDF: flex and grid layouts, floats, absolute positions, transforms, shadows, background images, columns,
::before/::aftercontent, counters, orphans / widows and@page :firstare not laid out as in a browser; external style sheets are not loaded. - Opened files: a JSON snapshot keeps only the added drawing; content added to an opened tagged file is not tagged; public-key (certificate) encryption is not opened; RC4 is not written.
- Annotations: no rich text in text boxes (one font, size and color), no cloud borders, callouts, measurements, attachments, sound or movie annotations; XFDF carries no images; stamps of other programs can be removed, not moved.
- Forms: combo boxes are drawn without the arrow, list boxes from the first option; rich text fields, comb fields, barcode fields, XFA forms and calculated fields are not supported; actions of buttons of opened files are not run.
- Redaction: a vector path crossing an area is clipped, its geometry stays in the file; embedded font subsets keep the glyphs of removed characters (the set of characters, not the text); text in annotation appearances is not searched (an annotation touching an area is removed whole); a page of another file drawn in a box is clipped, not redacted; the ready-made patterns follow common formats and can miss or over-match unusual ones — review the marks before applying them.
- Comparison: the text of annotations is not compared; images and graphics only through
visual(browser); multi-column pages compare in their drawing order. - Digital signatures: no network requests (time stamps, OCSP and CRLs only through your callbacks); name constraints and policies of certificate paths are not checked; the freshness of revocation data is reported, not enforced; one signer per signature.
- PDF/A and PDF/UA: PDF/A-1, PDF/A-4 and PDF/UA-2 are not offered; no CMYK output intent; the built-in checks cover the listed rules only (no reading-order, contrast or semantic checks).
- Templates: no rotation of elements, one font / size / color per text element, a repeated block cannot contain a table or another block, QR and Data Matrix have no quiet zone; the designer previews the first output page of each template page.
- Rendering: JPEG 2000 progression changes, real ICC profiles (CMYK is converted by a fitted formula), annotation
NoRotate/NoZoom, CCITT uncompressed mode and JBIG2 color extension are not drawn exactly; the worker needshttp(s)and the URL of the library file. - Viewer: links of opened files are not clickable; no drag of pages between two viewers; dragging pages is mouse / pen only (touch: use the buttons).
- Framework wrappers: functions in options are compared by reference; removing a prop does not reset the option to its default; Vue watches object props shallowly.
