VibeFox JS PDF — 演示
快速开始
纯 HTML
快速开始的文档在浏览器中生成,并立即在带页面缩略图的查看器中显示;查看器创建之后添加的一行会自动出现。Save PDF 下载该文件。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
addButtons([['Save PDF', () => doc.save('report.pdf')]]);
document.getElementById('app').style.height = '520px';
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('#app', { document: doc, sidebar: 'thumbnails', zoom: 0.75 });
doc.text('Added later: the preview updates by itself.');打开 PDF 文件
选择电脑上的任意 PDF 文件:它由库自身打开并绘制,不会上传任何内容。在此之前,查看器显示的是代码生成的文件。
document.getElementById('app').style.height = '500px';
const input = document.createElement('input');
input.type = 'file';
input.accept = 'application/pdf';
document.getElementById('app').before(input);
// a first file to show: a document of the library saved to PDF bytes and opened again
const sample = new VibeFoxJSPdf.PdfDocument();
sample.text('Choose a PDF file above', { size: 20, bold: true });
sample.text('It is opened in this page only; nothing is sent anywhere.');
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: await VibeFoxJSPdf.loadPdf(await sample.toBytes()), zoom: 0.75 });
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.getElementById('app').style.height = '440px';
const output = document.createElement('pre');
output.style.cssText = 'height: 40px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
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 });
show('pageCount: ' + report.pageCount + ', cursor: ' + JSON.stringify(report.cursor));
VibeFoxJSPdf.createPdfViewer('#app', { document: report, zoom: 0.75 });事件
查看器和文档的每个事件都会写入输出框。翻页、缩放或点击 Add text:文档会触发 change,查看器随之重新绘制。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '420px';
const output = document.createElement('pre');
output.style.cssText = 'height: 90px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const log = [];
const write = (line) => { log.unshift(line); show(...log.slice(0, 6)); };
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: report, zoom: 0.6 });
viewer.on('pageChange', (e) => write('pageChange: page ' + e.page + ' of ' + e.pages));
viewer.on('zoomChange', (e) => write('zoomChange: ' + Math.round(e.zoom * 100) + ' %'));
report.on('change', (e) => write('document change: ' + e.type));
write('events are listed here, the newest first');
addButtons([
['Next page', () => viewer.nextPage()],
['Zoom in', () => viewer.zoomIn()],
['Add text', () => report.page(0).text('Added at ' + new Date().toLocaleTimeString(), { x: 60, y: 460, size: 14, color: '#b91c1c' })],
]);状态快照
更改页面、缩放或旋转,点击 Save state,再次更改它们,然后点击 Restore state:查看器会回到已保存的视图。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '420px';
const output = document.createElement('pre');
output.style.cssText = 'height: 40px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: report, zoom: 0.6, sidebar: 'thumbnails' });
let saved = null;
show('no state saved yet');
addButtons([
['Save state', () => { saved = viewer.getState(); show('saved: ' + JSON.stringify(saved)); }],
['Change view', () => { viewer.goToPage(3); viewer.setZoom(0.9); viewer.rotate(90); viewer.hideSidebar(); }],
['Restore state', () => { if (saved) viewer.setState(saved); }],
]);创建文档
页面与流式排版
一本 Times 字体的 A5 书籍:两端对齐的段落自动延续到后续页面,然后是一张 A4 横向宽页,流式排版在 y 200 处继续。
document.getElementById('app').style.height = '480px';
const book = new VibeFoxJSPdf.PdfDocument({ format: 'A5', font: { family: 'times', size: 11 } });
book.text('Chapter 1', { size: 18, bold: true, marginBottom: 8 });
const paragraph = 'A long paragraph wraps inside the margins and continues on the next page when the page is full. ';
for (let i = 0; i < 6; i++) book.text(paragraph.repeat(8), { align: 'justify', paragraphGap: 6 });
book.moveDown(20); // empty space, pt
book.ensureSpace(120); // a new page unless 120 pt are left
book.addPage({ format: 'A4', orientation: 'landscape' });
book.setCursorY(200); // continue the flow at y 200 of the current page
book.text('A wide page.', { size: 24 });
VibeFoxJSPdf.createPdfViewer('#app', { document: book, sidebar: 'thumbnails', zoom: 0.7 });文本
右对齐的框内文本、框底部测量位置处的一条线,以及一段旋转的半透明图章文字。
document.getElementById('app').style.height = '440px';
const output = document.createElement('pre');
output.style.cssText = 'height: 30px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const doc = new VibeFoxJSPdf.PdfDocument();
doc.text('Invoice 2026-017', { size: 20, bold: true });
doc.text('Bold, italic and colored text in the standard fonts.', { italic: true, color: '#475569' });
const p = doc.page(0);
const box = p.text('Total: 1 250.00 EUR', { x: 350, y: 200, 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: 260, size: 28, color: '#16a34a', rotate: 15, opacity: 0.6 });
show('width of "Total": ' + p.measureText('Total', { size: 14, bold: true }).toFixed(1) + ' pt');
VibeFoxJSPdf.createPdfViewer('#app', { document: doc, zoom: 0.9 });形状与路径
一个圆形、一个三角形、一条贝塞尔曲线、一个圆角虚线框,以及一组被剪切路径裁切的半透明图形——全部为页面上的矢量图形。
document.getElementById('app').style.height = '380px';
const doc = new VibeFoxJSPdf.PdfDocument();
const pg = doc.addPage();
pg.drawCircle(80, 80, 20, { fill: '#fde68a', stroke: '#b45309', lineWidth: 1.5 });
pg.drawPolygon([[130, 100], [150, 60], [170, 100]], { fill: '#bfdbfe', close: true });
pg.drawPath([{ c: 'M', x: 200, y: 100 }, { c: 'C', x1: 220, y1: 50, x2: 260, y2: 110, x: 280, y: 70 }], { stroke: '#7c3aed', lineWidth: 2 });
pg.group({ opacity: 0.5, clip: [{ c: 'M', x: 300, y: 60 }, { c: 'L', x: 360, y: 60 }, { c: 'L', x: 360, y: 100 }, { c: 'L', x: 300, y: 100 }, { c: 'Z' }] }, (g) => {
g.drawRect(290, 50, 90, 60, { fill: '#ef4444' });
});
pg.drawRect(390, 55, 140, 50, { stroke: '#0f766e', lineWidth: 1.5, dash: [4, 3], radius: 10 });
pg.drawEllipse(300, 200, 220, 50, { fill: '#ecfeff', stroke: '#0891b2' });
pg.drawLine(80, 280, 520, 280, { color: '#64748b', width: 1, dash: [2, 2] });
VibeFoxJSPdf.createPdfViewer('#app', { document: doc, zoom: 0.9 });图像与 SVG
一张带透明度的 PNG(在示例中直接绘制到 canvas 中),由同一个已注册图像放置两次;以及一个带渐变的 SVG,以矢量图形绘制——放大即可看到它始终清晰。
document.getElementById('app').style.height = '460px';
// a PNG with transparency, made in a canvas (in your page: the bytes or a data URL of your image)
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 96;
const ctx = canvas.getContext('2d');
const grad = ctx.createRadialGradient(48, 40, 6, 48, 48, 46);
grad.addColorStop(0, '#fef08a');
grad.addColorStop(1, '#f97316');
ctx.fillStyle = grad;
ctx.beginPath();
ctx.arc(48, 48, 46, 0, Math.PI * 2);
ctx.fill();
const doc = new VibeFoxJSPdf.PdfDocument();
const logo = doc.addImage(canvas.toDataURL('image/png')); // registered once
doc.addPage().drawImage(logo, 50, 50, { width: 48 });
doc.moveDown(60);
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' });
VibeFoxJSPdf.createPdfViewer('#app', { document: doc, zoom: 0.75 });表格
一个 80 行的表格:表格行延续到三页,彩色表头行在每页重复出现。滚动页面或点击缩略图。
document.getElementById('app').style.height = '480px';
const output = document.createElement('pre');
output.style.cssText = 'height: 30px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const doc = new VibeFoxJSPdf.PdfDocument({ footer: { text: '{page} / {pages}', align: 'center', size: 9 } });
doc.text('Order lines', { size: 18, bold: true, marginBottom: 8 });
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,
});
show('pages: ' + res.pages + ', rows: ' + res.rows);
VibeFoxJSPdf.createPdfViewer('#app', { document: doc, sidebar: 'thumbnails', zoom: 0.7 });页眉、页脚和水印
页眉中的标题、页脚中的 "Page n of m",以及贯穿每一页的 DRAFT 水印;它们都绘制在全部三页上。
document.getElementById('app').style.height = '460px';
const doc = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Project plan' } });
for (let i = 1; i <= 3; i++) {
if (i > 1) doc.addPage();
doc.text('Section ' + i, { size: 18, bold: true, marginBottom: 8 });
doc.text('The header, the footer and the watermark are set once for the whole document. '.repeat(6));
}
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 });
VibeFoxJSPdf.createPdfViewer('#app', { document: doc, sidebar: 'thumbnails', zoom: 0.7 });链接、书签和元数据
侧边栏中带有一个嵌套子项的书签(单击即可打开对应页面),以及第 1 页上指向第 3 页的链接。元数据标题用作文档名称。
document.getElementById('app').style.height = '460px';
const doc = new VibeFoxJSPdf.PdfDocument();
['Contents', 'Terms', 'Payment'].forEach((title, i) => {
if (i) doc.addPage();
doc.text(title, { size: 22, bold: true, marginBottom: 10 });
});
const pageOne = doc.page(0);
pageOne.text('Go to the payment terms (page 3)', { x: 50, y: 100, color: '#2563eb' });
pageOne.drawLine(50, 115, 230, 115, { color: '#2563eb', width: 0.5 });
pageOne.link(50, 100, 200, 16, { page: 2, destY: 0 }); // to the third page
pageOne.link(50, 130, 200, 16, { url: 'https://example.com/terms' }); // external link
pageOne.text('example.com/terms (external link)', { x: 50, y: 130, color: '#2563eb' });
const chapter = doc.addBookmark('Terms', { page: 1 });
doc.addBookmark('Payment', { page: 2, parent: chapter }); // nested bookmark
doc.setMetadata({ title: 'Invoice 2026-001', author: 'Example Ltd', subject: 'Invoice', keywords: 'invoice, 2026' });
VibeFoxJSPdf.createPdfViewer('#app', { document: doc, sidebar: 'outline', zoom: 0.7 });保存
这些按钮以不同方式保存同一文档:下载、未压缩的文件,以及字节大小。查看器显示已保存的内容。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '400px';
const output = document.createElement('pre');
output.style.cssText = 'height: 40px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const doc = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Saved in the browser' } });
doc.text('Saved in the browser', { size: 20, bold: true });
doc.text('The file is written by the library: PDF 1.7, compressed when the browser has CompressionStream.');
doc.on('save', (e) => show('saved ' + e.filename + ', ' + e.size + ' bytes'));
show('press a button');
addButtons([
['Download', () => doc.save('saved.pdf')],
['Download uncompressed', () => doc.save('plain.pdf', { compress: false })],
['Size of the bytes', async () => show('toBytes(): ' + (await doc.toBytes()).length + ' bytes, without compression: ' + (await doc.toBytes({ compress: false })).length + ' bytes')],
]);
VibeFoxJSPdf.createPdfViewer('#app', { document: doc, zoom: 0.75 });JSON 快照与合并
文档被保存为 JSON,再从中恢复,然后两者合并为一个四页文档(缩略图中可见这些页面)。
document.getElementById('app').style.height = '460px';
const output = document.createElement('pre');
output.style.cssText = 'height: 30px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const doc = new VibeFoxJSPdf.PdfDocument();
doc.text('Original, page 1', { size: 20, bold: true });
doc.addPage();
doc.text('Original, page 2', { size: 20, bold: true });
const json = JSON.stringify(doc.toJSON());
const copy = VibeFoxJSPdf.PdfDocument.fromJSON(JSON.parse(json));
copy.page(0).text('Restored from JSON', { x: 50, y: 100, size: 16, color: '#b45309' });
const both = VibeFoxJSPdf.PdfDocument.merge(doc, copy);
show('JSON: ' + json.length + ' characters, merged pages: ' + both.pageCount);
VibeFoxJSPdf.createPdfViewer('#app', { document: both, sidebar: 'thumbnails', zoom: 0.6 });字体
标准字体
每个阅读器都具备的标准 PDF 字体:Helvetica、Times 和 Courier(含粗体和斜体)、Symbol 与 ZapfDingbats;拉丁文和西里尔文可以在同一行中使用。不加载任何字体文件。
document.getElementById('app').style.height = '480px';
const doc = new VibeFoxJSPdf.PdfDocument();
for (const family of ['helvetica', 'times', 'courier']) {
doc.text(family, { font: family, size: 16, bold: true, marginBottom: 2 });
doc.text('Regular: The quick brown fox · Привет, мир', { font: family });
doc.text('Bold: The quick brown fox', { font: family, bold: true });
doc.text('Italic: The quick brown fox', { font: family, italic: true });
doc.text('Bold italic: Grüße aus Köln', { font: family, bold: true, italic: true, marginBottom: 10 });
}
doc.text('abgdpWS αβγ ∑ √ ∞ ≠', { font: 'symbol', size: 18 }); // Greek letters and math signs
doc.text('3456789 ✔ ☎ ✈ ❶ ①', { font: 'zapfdingbats', size: 18 }); // dingbats
VibeFoxJSPdf.createPdfViewer('#app', { document: doc, zoom: 0.8 });HTML 转 PDF
一段带 CSS 的 HTML 字符串,由库进行排版:带样式的标题、链接、带边框的表格、列表和页脚。然后在新页面上添加第二部分。
document.getElementById('app').style.height = '500px';
const html = '<style>' +
'h1 { color: #0f766e; } table { border-collapse: collapse; width: 100%; }' +
'td, th { border: 1px solid #cbd5e1; padding: 4px 8px; } th { background: #f1f5f9; }' +
'.note { border-left: 4px solid #f59e0b; background: #fffbeb; padding: 6px 10px; }' +
'</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>' +
'<p class="note">Rounded numbers, in thousands of EUR.</p>' +
'<ol><li>Open a second shop</li><li>Hire two people</li></ol>';
const report = await VibeFoxJSPdf.htmlToPdf(html, {
format: 'A4',
footer: '<p style="text-align: right">{page} / {pages}</p>',
});
await report.addHtml('<h2>Notes</h2><ul><li>First</li><li>Second</li></ul>', { newPage: true });
VibeFoxJSPdf.createPdfViewer('#app', { document: report, sidebar: 'thumbnails', zoom: 0.7 });PDF 中的 VibeFox JS 组件
VibeFox JS Charts 的一张图表(位于查看器上方)以矢量图形绘制到 PDF 中,一次为全宽,两次按两列网格排列。放大查看:柱形和文字保持清晰。
document.getElementById('app').style.height = '440px';
// VibeFox JS Charts is also on the page (its file loaded)
const box = document.createElement('div');
box.style.cssText = 'width: 480px; max-width: 100%; height: 220px';
document.getElementById('app').before(box);
const chart = VibeFoxJSCharts.createChart(box, { categories: ['A', 'B', 'C', 'D'], series: [{ type: 'column', name: 'Sales', data: [5, 8, 3, 6] }] });
const report = new VibeFoxJSPdf.PdfDocument();
report.text('Sales by product', { size: 16, bold: true, marginBottom: 8 });
await report.addComponent(chart); // content width, the on-screen aspect ratio
await report.addComponents([chart, chart], { columns: 2, gap: 12, height: 160 }); // a layout grid
VibeFoxJSPdf.createPdfViewer('#app', { document: report, zoom: 0.7 });打开和修改 PDF 文件
打开一个 PDF 文件(此处由代码生成并保存为字节),为其添加 APPROVED 文字和 COPY 水印,然后以增量更新的方式保存。输出框显示库在文件中读取到的内容。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '420px';
const output = document.createElement('pre');
output.style.cssText = 'height: 50px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
// the bytes of a PDF file: from <input type="file">, fetch() or, as here, made by the library
const source = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Purchase order' } });
source.text('Purchase order 7781', { size: 20, bold: true });
source.text('Ten chairs and two tables, delivery in May.');
const fileBytes = await source.toBytes();
const pdf = await VibeFoxJSPdf.loadPdf(fileBytes);
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
show('version ' + pdf.sourceInfo.version + ', pages ' + pdf.pageCount + ', title "' + pdf.metadata.title + '"',
'original ' + fileBytes.length + ' bytes, with the update ' + updated.length + ' bytes');
addButtons([['Download', () => pdf.save('approved.pdf')]]);
VibeFoxJSPdf.createPdfViewer('#app', { document: pdf, zoom: 0.75 });页面操作
在一张横向页面上并排绘制一份文档的两页,然后是源文件在经过旋转、重新排序和缩减后的页面。
document.getElementById('app').style.height = '460px';
const doc = new VibeFoxJSPdf.PdfDocument();
['#dbeafe', '#dcfce7', '#fef9c3', '#fee2e2'].forEach((color, i) => {
const page = doc.addPage();
page.drawRect(40, 40, 515, 760, { fill: color, radius: 12 });
page.text('Page ' + (i + 1), { x: 60, y: 380, width: 475, align: 'center', size: 48, bold: true });
});
// 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 });
const pdf = await VibeFoxJSPdf.loadPdf(await doc.toBytes());
pdf.rotatePage(0, 90);
pdf.movePage(2, 0);
pdf.removePage(3);
const all = VibeFoxJSPdf.PdfDocument.merge(sheet, pdf);
VibeFoxJSPdf.createPdfViewer('#app', { document: all, sidebar: 'thumbnails', zoom: 0.5 });查看器
带工具栏的查看器:缩略图、页码输入框、上一页 / 下一页、缩放、适合宽度、旋转、搜索、打印和下载。它显示 classic 样式、第二页以及旋转后的视图。
document.getElementById('app').style.height = '520px';
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const v = VibeFoxJSPdf.createPdfViewer('#app', {
document: report,
page: 2, // the page to open (1-based)
zoom: 0.75, // 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: 'report.pdf', // name of the downloaded file
style: 'classic', // ready-made look (see Theming and styling)
});导航与缩放
这些按钮调用查看器的方法:翻页、缩放、适应、旋转以及单页布局。输出框显示每一步之后的状态。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '440px';
const output = document.createElement('pre');
output.style.cssText = 'height: 30px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: report, zoom: 0.6 });
const state = () => show(JSON.stringify(viewer.getState()));
viewer.on('pageChange', state);
viewer.on('zoomChange', state);
viewer.on('rotationChange', state);
addButtons([
['Previous', () => viewer.prevPage()],
['Next', () => viewer.nextPage()],
['Page 4', () => viewer.goToPage(4)],
['Zoom out', () => viewer.zoomOut()],
['Zoom in', () => viewer.zoomIn()],
['Fit width', () => viewer.fitWidth()],
['Fit page', () => viewer.fitPage()],
['Rotate', () => viewer.rotate(90)],
['Single page', () => viewer.setOptions({ layout: 'single' })],
['Continuous', () => viewer.setOptions({ layout: 'continuous' })],
]);侧边栏:缩略图、书签、图层、签名
侧边栏以树形显示报告的书签;按钮可将其切换为缩略图或将其关闭。单击书签或缩略图即可打开对应页面。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '440px';
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: report, sidebar: 'outline', zoom: 0.6 });
addButtons([
['Thumbnails', () => viewer.showSidebar('thumbnails')],
['Bookmarks', () => viewer.showSidebar('outline')],
['Hide', () => viewer.hideSidebar()],
]);一张带三个图层的平面图(可选内容,由 CAD 或桌面排版(DTP)软件制作)。可在 Layers 标签页中或通过按钮开启和关闭图层。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '460px';
// a small PDF file with three layers, written here by hand (usually it comes from a CAD or DTP program)
const objects = [
'<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R 6 0 R 7 0 R] /D << /Order [5 0 R 6 0 R 7 0 R] /ON [5 0 R 6 0 R 7 0 R] >> >> >>',
'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 8 0 R >> /Properties << /L1 5 0 R /L2 6 0 R /L3 7 0 R >> >> /Contents 4 0 R >>',
null,
'<< /Type /OCG /Name (Walls) >>',
'<< /Type /OCG /Name (Wiring) >>',
'<< /Type /OCG /Name (Furniture) >>',
'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',
];
const content = 'BT /F1 22 Tf 60 770 Td (Floor plan) Tj ET\n' +
'/OC /L1 BDC 0.2 0.2 0.2 RG 8 w 60 280 475 440 re S 300 280 m 300 560 l S EMC\n' +
'/OC /L2 BDC 0.92 0.35 0.05 RG 2 w [6 4] 0 d 90 690 m 270 690 l 270 320 l S 330 690 m 500 690 l 500 420 l S EMC\n' +
'/OC /L3 BDC 0.05 0.46 0.43 rg 110 330 120 70 re f 360 330 90 90 re f 400 600 m 400 627.6 377.6 650 350 650 c 322.4 650 300 627.6 300 600 c f EMC\n';
objects[3] = '<< /Length ' + content.length + ' >>\nstream\n' + content + 'endstream';
let text = '%PDF-1.7\n';
const offsets = objects.map((o, i) => { const at = text.length; text += (i + 1) + ' 0 obj\n' + o + '\nendobj\n'; return at; });
const xref = text.length;
text += 'xref\n0 ' + (objects.length + 1) + '\n0000000000 65535 f \n' + offsets.map((o) => String(o).padStart(10, '0') + ' 00000 n \n').join('') +
'trailer\n<< /Size ' + (objects.length + 1) + ' /Root 1 0 R >>\nstartxref\n' + xref + '\n%%EOF\n';
const plan = await VibeFoxJSPdf.loadPdf(new TextEncoder().encode(text));
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: plan, sidebar: 'layers', zoom: 0.6 });
let on = true;
addButtons([['Toggle wiring', () => { on = !on; viewer.setLayerVisible('Wiring', on); }]]);文本选择与搜索
单词 “invoice” 被找到并高亮显示(当前匹配项使用更醒目的颜色);点击 Next 跳到下一个匹配项。用鼠标选中文字并复制,或在查看器中按 Ctrl+F。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '440px';
const output = document.createElement('pre');
output.style.cssText = 'height: 30px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: report, zoom: 0.75 });
const report1 = (s) => s && show(s.total + ' matches, current ' + (s.index + 1) + ' on page ' + s.page);
report1(await viewer.search('invoice', { caseSensitive: false }));
addButtons([
['Next', () => report1(viewer.searchNext())],
['Previous', () => report1(viewer.searchPrev())],
['Search "sales"', async () => report1(await viewer.search('sales'))],
['Clear', () => { viewer.clearSearch(); show(''); }],
]);页面编辑
缩略图面板带有页面工具栏:选择缩略图(Ctrl / Shift + 单击),将其拖到新位置、旋转或删除,还可以撤销。这些按钮也可以通过代码执行相同的操作。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '460px';
const output = document.createElement('pre');
output.style.cssText = 'height: 30px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const ed = VibeFoxJSPdf.createPdfViewer('#app', { document: report, pageEditing: true, sidebar: 'thumbnails', zoom: 0.5 });
show('select thumbnails and use the page tool bar, or press the buttons');
ed.on('pageEdit', (e) => show(e.action + ' -> pages ' + e.pages.map((p) => p + 1).join(', ')));
addButtons([
['Rotate pages 1-2', () => { ed.selectPages([0, 1]); ed.rotatePages(); }],
['Page 3 to the front', () => ed.movePages([2], 0)],
['Delete page 4', () => ed.removePages([3])],
['Undo', () => ed.undo()],
['Redo', () => ed.redo()],
]);打印
工具栏中的打印按钮或 Print pages 1–2 会打开浏览器的打印对话框,页面以 200 dpi 绘制;输出框显示进度。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '420px';
const output = document.createElement('pre');
output.style.cssText = 'height: 30px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: report, zoom: 0.6 });
show('press Print pages 1-2 or the print button of the toolbar');
viewer.on('printProgress', (e) => show('prepared ' + e.done + ' of ' + e.total));
addButtons([['Print pages 1-2', async () => {
const result = await viewer.print({ pages: '1-2', dpi: 200 });
if (result) show('printed pages ' + result.pages.map((p) => p + 1).join(', ') + ' at ' + result.dpi + ' dpi');
}]]);不使用查看器绘制页面
报告的每一页以一半的尺寸分别绘制到各自的 canvas 中,不使用查看器组件。
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const app = document.getElementById('app');
app.style.cssText = 'display: flex; flex-wrap: wrap; gap: 8px';
for (let i = 0; i < report.pageCount; i++) {
const canvas = document.createElement('canvas');
canvas.style.border = '1px solid #cbd5e1';
app.append(canvas);
await VibeFoxJSPdf.renderPageToCanvas(report, i, canvas, { scale: 0.3, background: '#ffffff' });
}渲染 PDF 文件
renderer 选项与 pdf.js
使用库自带的渲染器(renderer: 'lite')绘制的已打开 PDF 文件:矢量图形、标准字体文本和一张透明图像;未使用 pdf.js。
document.getElementById('app').style.height = '440px';
// the bytes of a PDF file (made here by the library; a file from the user works the same way)
const source = new VibeFoxJSPdf.PdfDocument();
source.text('A file opened from bytes', { size: 20, bold: true });
source.svg('<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><circle cx="100" cy="100" r="90" fill="#0ea5e9" opacity=".5"/>' +
'<circle cx="140" cy="100" r="60" fill="#f97316" opacity=".6"/></svg>', { width: 160 });
const bytes = await source.toBytes();
VibeFoxJSPdf.useLiteWorker(true); // default: the own renderer runs in a worker
VibeFoxJSPdf.createPdfViewer('#app', { document: await VibeFoxJSPdf.loadPdf(bytes), renderer: 'lite', zoom: 0.75 });底层函数
使用 renderPageLite 将已打开文件的一页绘制到 canvas 中;它返回的文本项在其位置上以红色轮廓标出。
const source = new VibeFoxJSPdf.PdfDocument({ format: [320, 200], margins: { top: 30, right: 30, bottom: 30, left: 30 } });
source.text('Low-level rendering', { size: 16, bold: true });
source.text('renderPageLite paints the page and also returns the text items with their positions.');
const opened = await VibeFoxJSPdf.loadPdf(await source.toBytes());
const canvas = document.createElement('canvas');
canvas.style.border = '1px solid #cbd5e1';
document.getElementById('app').append(canvas);
const scale = 1.2;
const r = await VibeFoxJSPdf.renderPageLite(opened.page(0), canvas, { scale, text: true });
const ctx = canvas.getContext('2d');
const h = opened.page(0).height;
ctx.strokeStyle = '#dc2626';
for (const t of r.text) { // transform: PDF coordinates (from the bottom)
const [, , , , x, y] = t.transform;
ctx.strokeRect(x * scale, (h - y - t.height * 0.8) * scale, t.width * scale, t.height * scale);
}文本提取与搜索
库读取的报告文本;通过正则表达式找到的金额,以及通过现成模式找到的电子邮件地址,在查看器中以高亮注释标记。
document.getElementById('app').style.height = '400px';
const output = document.createElement('pre');
output.style.cssText = 'height: 60px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const { text, pages } = await report.extractText();
const amounts = await report.searchText(/\d[\d ]*\d EUR/);
const emails = await report.searchText('email');
for (const hit of amounts.concat(emails)) {
report.addAnnotation(hit.page, { type: 'highlight', rects: hit.rects, color: '#fde047' });
}
show(pages.length + ' pages, ' + text.length + ' characters: ' + text.slice(0, 60) + '…',
'found: ' + amounts.concat(emails).map((h) => 'page ' + (h.page + 1) + ': ' + h.text).join('; '));
VibeFoxJSPdf.createPdfViewer('#app', { document: report, page: 3, zoom: 0.6 });注释
通过代码添加
通过代码添加的高亮、便签图标、红色框、箭头、文本框和 APPROVED 图章;它们以真正的 PDF 注释形式保存。
document.getElementById('app').style.height = '460px';
const doc = new VibeFoxJSPdf.PdfDocument();
doc.text('Invoice 2026-017', { size: 20, bold: true });
doc.text('Total amount: 1 250.00 EUR', { size: 14 });
doc.addAnnotation(0, { type: 'highlight', rects: [[50, 82, 190, 20]], 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, 45, 200, 34], color: '#dc2626', width: 2 });
doc.addAnnotation(0, { type: 'line', points: [[300, 200], [250, 110]], arrow: true, color: '#2563eb' });
doc.addAnnotation(0, { type: 'freetext', rect: [300, 200, 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: [360, 260, 160, 40] }); // move / resize
VibeFoxJSPdf.createPdfViewer('#app', { document: doc, zoom: 0.9 });数据交换与拼合
文档的注释以 XFDF 格式导出(显示在输出框中),导入到一个副本中并在其中拼合:在对应页面上,它们成为页面内容的一部分,不能再编辑。
document.getElementById('app').style.height = '420px';
const output = document.createElement('pre');
output.style.cssText = 'height: 70px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const doc = new VibeFoxJSPdf.PdfDocument();
doc.text('Original with annotations', { size: 18, bold: true });
doc.addAnnotation(0, { type: 'rect', rect: [45, 40, 260, 34], color: '#dc2626', width: 2 });
doc.addAnnotation(0, { type: 'stamp', stamp: 'reviewed', x: 330, y: 120 });
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.page(0).text('Flattened copy', { x: 50, y: 90, size: 14, color: '#0f766e' });
copy.flatten({ annotations: true, forms: true }); // annotations become page content
show(xfdf);
VibeFoxJSPdf.createPdfViewer('#app', { document: VibeFoxJSPdf.PdfDocument.merge(doc, copy), zoom: 0.45, sidebar: 'thumbnails' });在查看器中
注释工具栏:选择高亮并选中文字、用墨迹绘制、拖出一个框或箭头、单击放置便签,或选择图章;选中注释即可移动、调整大小或删除。输出框列出已添加的内容。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '480px';
const output = document.createElement('pre');
output.style.cssText = 'height: 30px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const av = VibeFoxJSPdf.createPdfViewer('#app', { document: report, annotations: true, author: 'Anna', zoom: 0.75 });
show('pick a tool and draw on the page');
av.on('annotationAdd', (e) => show('added ' + e.annotation.type + ' on page ' + (e.page + 1)));
addButtons([
['Highlight', () => av.setTool('highlight')],
['Ink', () => av.setTool('ink')],
['Stamp "Paid"', () => av.placeStamp({ stamp: 'paid' })], // follows the pointer until a click
['Select', () => av.setTool('select')],
['Undo', () => av.undo()],
]);可视签名
一个手绘签名(带日期)和一个以系统草书字体输入的签名。点击 Sign 打开签名对话框(Draw、Type、Image),然后单击页面以放置签名。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '440px';
const doc = new VibeFoxJSPdf.PdfDocument();
doc.text('Delivery note 448', { size: 20, bold: true });
doc.text('Received in good condition.');
const sig = VibeFoxJSPdf.drawnSignature([[[0, 20], [10, 2], [20, 28], [32, 4], [44, 26], [56, 6], [70, 22], [84, 10]]], { color: '#1e3a8a' });
doc.page(0).addSignature(sig, 50, 130, { width: 140, date: true, author: 'Anna Berg' });
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: doc, annotations: true, zoom: 0.9 });
viewer.addSignature(VibeFoxJSPdf.typedSignature('Anna Berg'), { page: 1, x: 320, y: 130, width: 160 });
addButtons([['Sign', () => viewer.openSignatureDialog()]]);表单
创建字段
通过代码创建的可填写表单:带数字和电子邮件格式的文本字段、复选框、单选按钮、组合框、列表、签名字段和按钮。直接在此处填写。
document.getElementById('app').style.height = '520px';
const form = new VibeFoxJSPdf.PdfDocument();
const fp = form.addPage();
fp.text('Order form', { x: 50, y: 20, size: 18, bold: true });
[['Name', 60], ['Amount', 90], ['E-mail', 120], ['Terms', 150], ['Plan', 180], ['Country', 210], ['Region', 240], ['Signature', 315]]
.forEach(([label, y]) => fp.text(label, { x: 50, y, size: 11 }));
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.text('basic', { x: 168, y: 180, size: 9 });
fp.text('pro', { x: 238, y: 180, size: 9 });
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' });
VibeFoxJSPdf.createPdfViewer('#app', { document: form, forms: true, zoom: 0.9 });填写与读取
表单通过代码填写;输出框显示回读的值、检查结果以及以 XFDF 导出的数据。Reset amount 和 Fill again 同样会更改查看器中的字段。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '380px';
const output = document.createElement('pre');
output.style.cssText = 'height: 110px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const form = new VibeFoxJSPdf.PdfDocument();
const fp = form.addPage();
['Name', 'Amount', 'Terms', 'Country'].forEach((label, i) => fp.text(label, { x: 50, y: 60 + i * 30, size: 11 }));
fp.addTextField('name', 150, 55, 200, { required: true });
fp.addTextField('amount', 150, 85, 100, { format: { type: 'number', decimals: 2, min: 0 }, align: 'right' });
fp.addCheckbox('terms', 150, 115);
fp.addComboBox('country', 150, 145, 150, { options: ['Norway', 'Sweden', { value: 'FI', label: 'Finland' }] });
const report = () => {
const check = form.validateForm(); // { valid, errors: [{ name, code, message }] }
show('values: ' + JSON.stringify(form.getFieldValues()),
'valid: ' + check.valid + (check.errors.length ? ' (' + check.errors.map((e) => e.name + ': ' + e.code).join(', ') + ')' : ''),
form.exportFormData({ format: 'xfdf' }));
};
form.setFieldValues({ name: 'Anna Berg', amount: '42', terms: true, country: 'FI' });
report();
addButtons([
['Reset amount', () => { form.resetForm(['amount']); report(); }],
['Fill again', () => { form.setFieldValues({ amount: '99.5' }); report(); }],
]);
VibeFoxJSPdf.createPdfViewer('#app', { document: form, forms: true, zoom: 0.8 });在查看器中填写
在字段中输入内容:每次更改都会写入输出框。Send 并不会发送任何内容:它检查表单,标记必填的空字段,并将这些值交给代码处理。
document.getElementById('app').style.height = '380px';
const output = document.createElement('pre');
output.style.cssText = 'height: 60px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const form = new VibeFoxJSPdf.PdfDocument();
const fp = form.addPage();
fp.text('Name *', { x: 50, y: 60, size: 11 });
fp.text('E-mail', { x: 50, y: 90, size: 11 });
fp.addTextField('name', 150, 55, 200, { required: true, tooltip: 'Name' });
fp.addTextField('email', 150, 85, 200, { format: 'email', tooltip: 'E-mail' });
fp.addButton('send', 150, 125, 80, 24, { label: 'Send', action: { submit: 'https://example.com/form', format: 'xfdf' } });
const fv = VibeFoxJSPdf.createPdfViewer('#app', { document: form, forms: true, zoom: 0.9 });
show('type into the fields, then press Send');
fv.on('fieldChange', (e) => show(e.name + ' = ' + JSON.stringify(e.value)));
fv.on('formSubmit', (e) => show(e.valid ? 'send these values yourself: ' + JSON.stringify(e.values) : 'not valid: ' + e.errors.map((x) => x.message).join('; ')));脱敏
电子邮件地址和电话号码已标记为待脱敏(红色框,列在面板中)。点击 Apply redactions:标记下方的文字会从文件中删除,并绘制黑色框;然后搜索该地址——已无法找到。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '460px';
const output = document.createElement('pre');
output.style.cssText = 'height: 30px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const marks = await report.redactText(['email', 'phone'], { text: 'REMOVED' });
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: report, redaction: true, page: 3, zoom: 0.6 });
viewer.toggleRedactionList(true);
show(marks.length + ' marks: ' + marks.map((m) => m.match).join(', '));
addButtons([['Apply redactions', async () => {
const result = await viewer.applyRedactions();
if (result) show('removed: ' + result.removed.text + ' characters, ' + result.marks + ' marks');
}], ['Search "example.com"', async () => {
const hits = await report.searchText('example.com');
show('example.com found ' + hits.length + ' times');
}]]);文档比较
比较视图
合同的两个版本并排显示并同步滚动:旧版本中标出删除的词,新版本中标出插入的词,并列出所有更改。Next change 和 Overlay 调用相应的方法。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '500px';
const contract = (price, days, extra) => {
const d = new VibeFoxJSPdf.PdfDocument();
d.text('Supply contract', { size: 20, bold: true, marginBottom: 10 });
d.text('The supplier delivers ten chairs and two tables to the buyer. The price is ' + price + ' EUR, paid within ' + days + ' days after the delivery.');
d.text('The goods are delivered to the shop of the buyer in Oslo.' + extra);
return d.toBytes();
};
const oldBytes = await contract('1 250', 30, '');
const newBytes = await contract('1 400', 14, ' Delivery is free of charge.');
const cv = VibeFoxJSPdf.createPdfCompare('#app', { from: oldBytes, to: newBytes, layout: 'side', list: true, zoom: 0.6 });
addButtons([
['Next change', () => cv.nextChange()],
['Overlay', () => cv.setLayout('overlay')],
['Side by side', () => cv.setLayout('side')],
['HTML report', () => cv.downloadReport('html')],
]);数字签名
签名
在浏览器中使用 WebCrypto 和写入代码的测试证书对一份合同进行签名;已签名的文件在查看器中打开,查看器会检查签名,并在状态栏和 Signatures 标签页中显示结果。
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
document.getElementById('app').style.height = '520px';
// a test key and certificate (EC P-256, issued by a test root CA); in a real page: the user's .p12 file and password
const KEY = '-----BEGIN PRIVATE KEY-----\n' +
'MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgf3aXiL7utR4YWaMr\n' +
'gXP4APnDYB32vK5jw1yEVrF/zSChRANCAAQ9PMZ14PuMmLqVMYXKsNmALZUdSJy8\n' +
'Ne8gVsiQHrmHJ2Z5Oc8/qee5NTcXTaWLoId15h80MeUa7FUXuWX/sWIT\n' +
'-----END PRIVATE KEY-----';
const CERTIFICATE = '-----BEGIN CERTIFICATE-----\n' +
'MIIB4TCCAYagAwIBAgICA+kwCgYIKoZIzj0EAwIwUTELMAkGA1UEBhMCTk8xHDAa\n' +
'BgNVBAoME1ZpYmVGb3ggSlMgUERGIGRlbW8xJDAiBgNVBAMMG1ZpYmVGb3ggSlMg\n' +
'UERGIERlbW8gUm9vdCBDQTAeFw0yNjAxMDEwMDAwMDBaFw0zNjAxMDEwMDAwMDBa\n' +
'MD8xCzAJBgNVBAYTAk5PMRwwGgYDVQQKDBNWaWJlRm94IEpTIFBERiBkZW1vMRIw\n' +
'EAYDVQQDDAlBbm5hIEJlcmcwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQ9PMZ1\n' +
'4PuMmLqVMYXKsNmALZUdSJy8Ne8gVsiQHrmHJ2Z5Oc8/qee5NTcXTaWLoId15h80\n' +
'MeUa7FUXuWX/sWITo2AwXjAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIGwDAd\n' +
'BgNVHQ4EFgQU8Tx072BdCKzf8frOUCWvooXeP7cwHwYDVR0jBBgwFoAUKj3gs+Yq\n' +
'irMa5H2ELdw2kE3Rb6IwCgYIKoZIzj0EAwIDSQAwRgIhANNqjiZPIDkenUwPGp2/\n' +
'IaJUiKb79y4ZQIwpdOF5VLVVAiEA0Zyk6WggkVewnX3zcD8WH3cLbbQiTGDwCj9x\n' +
'HjMn6LA=\n' +
'-----END CERTIFICATE-----';
const ROOT = '-----BEGIN CERTIFICATE-----\n' +
'MIIB9DCCAZugAwIBAgICA+gwCgYIKoZIzj0EAwIwUTELMAkGA1UEBhMCTk8xHDAa\n' +
'BgNVBAoME1ZpYmVGb3ggSlMgUERGIGRlbW8xJDAiBgNVBAMMG1ZpYmVGb3ggSlMg\n' +
'UERGIERlbW8gUm9vdCBDQTAeFw0yNjAxMDEwMDAwMDBaFw0zNjAxMDEwMDAwMDBa\n' +
'MFExCzAJBgNVBAYTAk5PMRwwGgYDVQQKDBNWaWJlRm94IEpTIFBERiBkZW1vMSQw\n' +
'IgYDVQQDDBtWaWJlRm94IEpTIFBERiBEZW1vIFJvb3QgQ0EwWTATBgcqhkjOPQIB\n' +
'BggqhkjOPQMBBwNCAATo7kfiZysjnumTeCWdAnUWDe8vvFg3hQCMLQw2QoYt3Za4\n' +
'L2cqO7scSj7aC1CJ+spEtSZ1cos+h92jciLt/s+yo2MwYTAPBgNVHRMBAf8EBTAD\n' +
'AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUKj3gs+YqirMa5H2ELdw2kE3R\n' +
'b6IwHwYDVR0jBBgwFoAUKj3gs+YqirMa5H2ELdw2kE3Rb6IwCgYIKoZIzj0EAwID\n' +
'RwAwRAIgHVcAcrYTfj6KZg4o8YwGUIGkUDCTkZeJ/yoa67ana4wCIBJ/B25tsFmF\n' +
'x9Jo+OdOHcFTC6qRdHo8P4UlU+3pXn4I\n' +
'-----END CERTIFICATE-----';
const pkcs8 = Uint8Array.from(atob(KEY.replace(/-----[^-]+-----|\s/g, '')), (ch) => ch.charCodeAt(0));
const key = await crypto.subtle.importKey('pkcs8', pkcs8, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']);
const doc = new VibeFoxJSPdf.PdfDocument();
doc.text('Supply contract 14', { size: 20, bold: true });
doc.text('The supplier delivers ten chairs and two tables to the buyer.');
const signed = await VibeFoxJSPdf.signPdf(doc, {
key,
certificate: CERTIFICATE,
chain: [ROOT],
reason: 'Approved',
location: 'Oslo',
page: 0,
rect: [50, 120, 260, 60], // visible signature box; no rect = invisible
appearance: { signature: VibeFoxJSPdf.typedSignature('Anna Berg') },
});
const viewer = VibeFoxJSPdf.createPdfViewer('#app', {
document: await VibeFoxJSPdf.loadPdf(signed),
sidebar: 'signatures',
signatureValidation: { trusted: ROOT }, // the roots you trust
zoom: 0.75,
});
addButtons([['Download signed PDF', () => viewer.download()]]);验证
已签名的合同分别以测试根证书为受信任证书(有效)和不信任任何证书(签名者未知)进行检查;然后在签名之后向页面添加文字,查看器在状态栏和 Signatures 标签页中显示针对该版本的检查结果。
document.getElementById('app').style.height = '440px';
const output = document.createElement('pre');
output.style.cssText = 'height: 90px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
// the same test key and certificates as in the Signing example
const KEY = 'MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgf3aXiL7utR4YWaMrgXP4APnDYB32vK5jw1yEVrF/zSChRANCAAQ9PMZ14PuMmLqVMYXKsNmALZUdSJy8Ne8gVsiQHrmHJ2Z5Oc8/qee5NTcXTaWLoId15h80MeUa7FUXuWX/sWIT';
const CERTIFICATE = '-----BEGIN CERTIFICATE-----\n' +
'MIIB4TCCAYagAwIBAgICA+kwCgYIKoZIzj0EAwIwUTELMAkGA1UEBhMCTk8xHDAaBgNVBAoME1ZpYmVGb3ggSlMgUERGIGRlbW8xJDAiBgNVBAMMG1ZpYmVGb3ggSlMg' +
'UERGIERlbW8gUm9vdCBDQTAeFw0yNjAxMDEwMDAwMDBaFw0zNjAxMDEwMDAwMDBaMD8xCzAJBgNVBAYTAk5PMRwwGgYDVQQKDBNWaWJlRm94IEpTIFBERiBkZW1vMRIw' +
'EAYDVQQDDAlBbm5hIEJlcmcwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQ9PMZ14PuMmLqVMYXKsNmALZUdSJy8Ne8gVsiQHrmHJ2Z5Oc8/qee5NTcXTaWLoId15h80' +
'MeUa7FUXuWX/sWITo2AwXjAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIGwDAdBgNVHQ4EFgQU8Tx072BdCKzf8frOUCWvooXeP7cwHwYDVR0jBBgwFoAUKj3gs+Yq' +
'irMa5H2ELdw2kE3Rb6IwCgYIKoZIzj0EAwIDSQAwRgIhANNqjiZPIDkenUwPGp2/IaJUiKb79y4ZQIwpdOF5VLVVAiEA0Zyk6WggkVewnX3zcD8WH3cLbbQiTGDwCj9x' +
'HjMn6LA=\n' +
'-----END CERTIFICATE-----';
const ROOT = '-----BEGIN CERTIFICATE-----\n' +
'MIIB9DCCAZugAwIBAgICA+gwCgYIKoZIzj0EAwIwUTELMAkGA1UEBhMCTk8xHDAaBgNVBAoME1ZpYmVGb3ggSlMgUERGIGRlbW8xJDAiBgNVBAMMG1ZpYmVGb3ggSlMg' +
'UERGIERlbW8gUm9vdCBDQTAeFw0yNjAxMDEwMDAwMDBaFw0zNjAxMDEwMDAwMDBaMFExCzAJBgNVBAYTAk5PMRwwGgYDVQQKDBNWaWJlRm94IEpTIFBERiBkZW1vMSQw' +
'IgYDVQQDDBtWaWJlRm94IEpTIFBERiBEZW1vIFJvb3QgQ0EwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATo7kfiZysjnumTeCWdAnUWDe8vvFg3hQCMLQw2QoYt3Za4' +
'L2cqO7scSj7aC1CJ+spEtSZ1cos+h92jciLt/s+yo2MwYTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUKj3gs+YqirMa5H2ELdw2kE3R' +
'b6IwHwYDVR0jBBgwFoAUKj3gs+YqirMa5H2ELdw2kE3Rb6IwCgYIKoZIzj0EAwIDRwAwRAIgHVcAcrYTfj6KZg4o8YwGUIGkUDCTkZeJ/yoa67ana4wCIBJ/B25tsFmF' +
'x9Jo+OdOHcFTC6qRdHo8P4UlU+3pXn4I\n' +
'-----END CERTIFICATE-----';
const pkcs8 = Uint8Array.from(atob(KEY), (ch) => ch.charCodeAt(0));
const key = await crypto.subtle.importKey('pkcs8', pkcs8, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']);
const doc = new VibeFoxJSPdf.PdfDocument();
doc.text('Supply contract 14', { size: 20, bold: true });
const signed = await VibeFoxJSPdf.signPdf(doc, { key, certificate: CERTIFICATE, chain: [ROOT], reason: 'Approved' });
const line = (title, r) => title + ': ' + r.status + ' — ' + r.signatures.map((s) =>
s.signer.commonName + ', ' + s.status + ', certificate ' + (s.certificate ? s.certificate.status : '-') + ', changes after signing: ' + s.modifications.changes.length).join('; ');
const trusted = await VibeFoxJSPdf.verifyPdf(signed, { trusted: ROOT });
const nothingTrusted = await VibeFoxJSPdf.verifyPdf(signed);
const changed = await VibeFoxJSPdf.loadPdf(signed);
changed.page(0).text('Price changed after signing', { x: 50, y: 300, color: '#dc2626' });
const afterChange = await VibeFoxJSPdf.verifyPdf(await changed.toBytes(), { trusted: ROOT });
show(line('trusted root', trusted), line('nothing trusted', nothingTrusted), line('page changed after signing', afterChange));
VibeFoxJSPdf.createPdfViewer('#app', { document: await VibeFoxJSPdf.loadPdf(await changed.toBytes()), signatureValidation: { trusted: ROOT }, sidebar: 'signatures', zoom: 0.6 });加密与权限
一份使用 AES-256 加密保存的文档:无需密码即可打开,但不允许打印或复制:查看器可以打开它,其打印按钮被禁用。输出框显示从文件中读取的权限。
document.getElementById('app').style.height = '380px';
const output = document.createElement('pre');
output.style.cssText = 'height: 50px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const doc = new VibeFoxJSPdf.PdfDocument();
doc.text('Confidential price list', { size: 20, bold: true });
doc.text('Opens without a password; printing and copying are not allowed.');
doc.setEncryption({
userPassword: '', // opens without a password
ownerPassword: 'owner-secret',
permissions: { copy: false, modify: false, print: false },
});
const protectedBytes = await doc.toBytes();
const opened = await VibeFoxJSPdf.loadPdf(protectedBytes);
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: opened, zoom: 0.8 });
const e = opened.sourceInfo.encrypted;
show(e.method + ', allowed: ' + Object.entries(e.allowed).filter(([, v]) => v).map(([k]) => k).join(', '),
'not allowed: ' + Object.entries(e.allowed).filter(([, v]) => !v).map(([k]) => k).join(', ') + '; canPrint(): ' + viewer.canPrint());PDF/A、PDF/UA 与标记 PDF
结构
带标记的文档:标题、段落、列表、带替代文本的图形和表格;输出框显示屏幕阅读器使用的结构树。
document.getElementById('app').style.height = '380px';
const output = document.createElement('pre');
output.style.cssText = 'height: 130px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const doc = new VibeFoxJSPdf.PdfDocument({ tagged: true, lang: 'en-US', metadata: { title: 'Annual report 2026' } });
doc.text('Annual report', { size: 20, tag: 'H1' });
doc.text('Revenue grew by 12 %.'); // a P element
doc.svg('<svg xmlns="http://www.w3.org/2000/svg" width="120" height="60"><rect width="120" height="60" rx="8" fill="#0f766e"/></svg>', { width: 80, alt: 'Company logo' });
doc.tag('L', () => {
doc.tag('LI', () => doc.text('First point'));
doc.tag('LI', () => doc.text('Second point'));
});
doc.table({ columns: [{ header: 'Region', field: 'r' }, { header: 'Sales', field: 's', align: 'right' }], rows: [{ r: 'North', s: 120 }, { r: 'South', s: 98 }] });
const tree = (node, depth = 0) => ' '.repeat(depth) + node.role + (node.alt ? ' (alt: ' + node.alt + ')' : '') + '\n' +
(node.children || []).map((child) => tree(child, depth + 1)).join('');
show(tree(doc.getStructure()));
VibeFoxJSPdf.createPdfViewer('#app', { document: doc, zoom: 0.8 });检查与转换
内置检查在一份普通文档上运行:列出 PDF/A-2b 和 PDF/UA 错误及标准条款,然后转换为 PDF/A,并显示已修复和无法修复的内容(标准字体不会嵌入;如需嵌入,请提供自有的字体文件)。
const output = document.createElement('pre');
output.style.cssText = 'height: 240px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const show = (...lines) => { output.textContent = lines.join('\n'); };
const doc = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Price list' } });
doc.text('Price list', { size: 20, bold: true });
const pdfBytes = await doc.toBytes();
const list = (items) => items.map((e) => ' ' + e.rule + ' ' + e.message).join('\n');
const pdfaReport = await VibeFoxJSPdf.checkPdfA(pdfBytes, { part: 2, conformance: 'b' });
const uaReport = await VibeFoxJSPdf.checkPdfUA(pdfBytes);
const { report } = await VibeFoxJSPdf.convertToPdfA(pdfBytes, { pdfa: '2b' });
show('PDF/A-2b conforms: ' + pdfaReport.conforms, list(pdfaReport.errors),
'PDF/UA-1 conforms: ' + uaReport.conforms, list(uaReport.errors),
'convertToPdfA fixed:', list(report.fixed), 'could not fix:', list(report.failed));模板与设计器
模板
一份带占位符、表达式和过滤器的发票模板,包含 QR 码和 EAN-13 条形码,并已填入数据;表格在页脚中对其各行求和。备注行(comment)是一个可填写字段。
document.getElementById('app').style.height = '500px';
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: 200, 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: 380, width: 300, height: 20, text: '{{paid ? "PAID" : "DUE"}} by {{due | date:dd.MM.yyyy}}', if: 'total > 0', bold: true },
{ type: 'barcode', format: 'ean13', x: 40, y: 420, width: 160, height: 60, value: '4006381333931' },
{ type: 'textfield', name: 'comment', x: 40, y: 500, width: 300, height: 24, tooltip: 'Comment' },
] }],
};
const data = { number: 'A-17', paid: false, total: 1250, due: '2026-11-30', 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' });
VibeFoxJSPdf.createPdfViewer('#app', { document: invoice, forms: true, zoom: 0.75 });设计器
带预览数据的模板设计器:从面板将元素拖到页面上,通过吸附功能选择、移动和调整其大小,在侧边面板中编辑其属性,并可撤销和重做。
document.getElementById('app').style.height = '620px';
const template = {
name: 'Invoice',
page: { format: 'A4' },
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: 160, data: 'items', columns: [
{ header: 'Item', value: '{{name}}', width: 3 },
{ header: 'Qty', value: '{{qty}}', align: 'right' },
{ header: 'Price', value: '{{price | number:2}}', align: 'right' },
] },
] }],
};
const data = { number: 'A-17', customer: { name: 'Anna Berg', city: 'Oslo' },
items: [{ name: 'Widget', qty: 2, price: 450 }, { name: 'Gadget', qty: 1, price: 350 }] };
const designer = VibeFoxJSPdf.createPdfDesigner('#app', { template, data, preview: true, zoom: 'fit' });
const el = designer.addElement('text', { x: 40, y: 340, width: 300, height: 20, text: 'Thank you, {{customer.name}}!' });
designer.select(el.id);
designer.align('center', { to: 'page' });主题与样式
主题
从列表中选择主题:内置的浅色、深色和高对比度主题,vibefox-js-themes.css 主题包,以及通过 registerTheme 注册的自定义主题 “brand”。
function addSelect(label, values, onChange) {
const select = document.createElement('select');
select.setAttribute('aria-label', label);
for (const value of values) select.append(new Option(label + ': ' + value, value));
select.onchange = () => onChange(select.value);
document.getElementById('app').before(select);
return select;
}
document.getElementById('app').style.height = '420px';
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
VibeFoxJSPdf.registerTheme('brand', { accent: '#e11d48', 'accent-fg': '#ffffff', radius: '10px' });
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: report, sidebar: 'thumbnails', zoom: 0.5 });
addSelect('Theme', ['light', 'dark', 'high-contrast', 'paper', 'glass', 'classic', 'ocean', 'ocean-dark', 'forest', 'sunset', 'graphite-dark', 'brand'],
(theme) => viewer.setTheme(theme));CSS 变量
查看器元素上设置了若干 --vfjs-pdf-* 变量:深色工具栏和深色按钮、灰色工作区、页面之间更宽的间距且无阴影,以及青绿色强调色。
document.getElementById('app').style.height = '420px';
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const style = document.createElement('style');
style.textContent = '.vfjs { --vfjs-accent: #0f766e; --vfjs-radius: 4px; }' +
'#app { --vfjs-pdf-bg: #e2e8f0; --vfjs-pdf-page-gap: 24px; --vfjs-pdf-page-shadow: none;' +
' --vfjs-pdf-toolbar-bg: #0f172a; --vfjs-pdf-toolbar-fg: #e2e8f0; --vfjs-pdf-muted: #94a3b8;' +
' --vfjs-pdf-btn-bg: #1e293b; --vfjs-pdf-btn-fg: #e2e8f0; --vfjs-pdf-btn-border: #334155; --vfjs-pdf-btn-hover-bg: #334155; }';
document.head.append(style);
VibeFoxJSPdf.createPdfViewer('#app', { document: report, zoom: 0.5 });现成样式
查看器的现成外观:从列表中选择 classic、dark、minimal、compact 或 paper。
function addSelect(label, values, onChange) {
const select = document.createElement('select');
select.setAttribute('aria-label', label);
for (const value of values) select.append(new Option(label + ': ' + value, value));
select.onchange = () => onChange(select.value);
document.getElementById('app').before(select);
return select;
}
document.getElementById('app').style.height = '420px';
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: report, sidebar: 'thumbnails', zoom: 0.5, style: 'classic' });
addSelect('Style', VibeFoxJSPdf.PDF_VIEWER_STYLES, (style) => viewer.setStyle(style));密度与尺寸
容器的密度会改变工具栏和侧边栏的高度与内边距;可选择 compact、normal 或 comfortable。
function addSelect(label, values, onChange) {
const select = document.createElement('select');
select.setAttribute('aria-label', label);
for (const value of values) select.append(new Option(label + ': ' + value, value));
select.onchange = () => onChange(select.value);
document.getElementById('app').before(select);
return select;
}
document.getElementById('app').style.height = '420px';
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: report, sidebar: 'thumbnails', zoom: 0.5 });
document.body.dataset.vfjsDensity = 'compact';
addSelect('Density', ['compact', 'normal', 'comfortable'], (density) => { document.body.dataset.vfjsDensity = density; });本地化与 RTL
语言
查看器显示为俄语,俄语语言包 vibefox-js-pdf.ru.js 在库之后加载;英语已内置。使用列表切换语言。PDF 文件本身的文字不会改变。
function addSelect(label, values, onChange) {
const select = document.createElement('select');
select.setAttribute('aria-label', label);
for (const value of values) select.append(new Option(label + ': ' + value, value));
select.onchange = () => onChange(select.value);
document.getElementById('app').before(select);
return select;
}
document.getElementById('app').style.height = '420px';
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: report, sidebar: 'thumbnails', zoom: 0.5, locale: 'ru' });
addSelect('Language', ['ru', 'en'], (locale) => viewer.setOptions({ locale }));添加语言
通过 addLocale 添加的部分德语词典:缩放和下载按钮显示为德语,词典中没有的键会回退为英语。将鼠标悬停在按钮上可查看工具提示。
document.getElementById('app').style.height = '420px';
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
VibeFoxJSPdf.addLocale('de', {
pdfZoomIn: 'Vergrößern',
pdfZoomOut: 'Verkleinern',
pdfDownload: 'PDF herunterladen',
});
VibeFoxJSPdf.createPdfViewer('#app', { document: report, zoom: 0.5, locale: 'de' });从右到左(RTL)
查看器采用从右到左的排版:工具栏和侧边栏被镜像,上一页 / 下一页按钮指向阅读方向;页面保持其几何结构。
document.getElementById('app').style.height = '420px';
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
VibeFoxJSPdf.createPdfViewer('#app', { document: report, sidebar: 'thumbnails', zoom: 0.5, rtl: true });与其他 VibeFox JS 库配合使用
使用 link() 连接组件
两个通过 link() 连接的查看器:翻动左侧查看器的页面,右侧查看器随之同步。
const report = new VibeFoxJSPdf.PdfDocument({ metadata: { title: 'Annual report 2026' }, footer: { text: 'Page {page} of {pages}', align: 'right', size: 9 } });
const chapters = [
['Introduction', 'This report describes the year of a small company that makes garden furniture. Sales grew in every region, and the new online shop brought many first-time customers.'],
['Sales', 'Sales reached 4.2 million EUR, 12 % more than last year. Chairs and tables sold best; the invoice total of the largest order was 48 000 EUR.'],
['Customers', 'Most customers are families and small cafes. Write to [email protected] or call +47 22 33 44 55 for a catalog.'],
['Outlook', 'Next year the company plans a second workshop and a winter collection. The search below finds the word invoice on page 2.'],
];
chapters.forEach(([title, body], i) => {
if (i) report.addPage();
report.addBookmark(title, { page: i });
report.text((i + 1) + '. ' + title, { size: 22, bold: true, color: '#0f766e', marginBottom: 10 });
report.text(body + ' ' + body, { size: 12, align: 'justify', marginBottom: 14 });
const page = report.page(i);
[60, 95, 75, 120, 105].forEach((h, j) => page.drawRect(70 + j * 90, 420 - h, 60, h, { fill: ['#99f6e4', '#5eead4', '#2dd4bf', '#14b8a6', '#0d9488'][j] }));
page.drawLine(60, 420, 520, 420, { color: '#64748b', width: 1 });
});
const app = document.getElementById('app');
app.style.cssText = 'display: grid; grid-template-columns: 1fr 1fr; gap: 8px; height: 400px';
const left = document.createElement('div');
const right = document.createElement('div');
app.append(left, right);
const viewer = VibeFoxJSPdf.createPdfViewer(left, { document: report, zoom: 0.4, layout: 'single' });
const second = VibeFoxJSPdf.createPdfViewer(right, { document: report, zoom: 0.4, layout: 'single', toolbar: false });
const unlink = VibeFoxJSPdf.link(viewer, 'pageChange', second, 'goToPage', (e) => e.page);