VibeFox JS PDF — Démo
Démarrage rapide
HTML simple
Le document du démarrage rapide, créé dans le navigateur et affiché aussitôt dans la visionneuse avec les miniatures des pages ; la ligne ajoutée après la création de la visionneuse apparaît d'elle-même. Save PDF télécharge le fichier.
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.');Ouvrir un fichier PDF
Choisissez n'importe quel fichier PDF de votre ordinateur : il est ouvert et dessiné par la bibliothèque elle-même, rien n'est envoyé. Jusque-là, la visionneuse montre un fichier créé dans le code.
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
};Concepts de base
Documents et pages
Du texte en flux depuis la marge supérieure et un cadre placé à des coordonnées exactes de la page (en points, depuis le coin supérieur gauche). La ligne sous la visionneuse indique le nombre de pages et le curseur de flux.
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 });Événements
Chaque événement de la visionneuse et du document est écrit dans la zone. Tournez les pages, zoomez ou cliquez sur Add text : le document émet change et la visionneuse le redessine.
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' })],
]);Instantanés de l'état
Changez la page, le zoom ou la rotation, cliquez sur Save state, modifiez-les à nouveau, puis cliquez sur Restore state : la visionneuse revient à la vue enregistrée.
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); }],
]);Création de documents
Pages et flux
Un livre au format A5 en Times : un paragraphe justifié qui passe seul sur les pages suivantes, puis une page A4 paysage plus large sur laquelle le flux continue à 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 });Texte
Un texte dans un cadre aligné à droite, une ligne sous celui-ci à la limite inférieure mesurée du cadre, et un texte de tampon pivoté et semi-transparent.
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 });Formes et tracés
Un cercle, un triangle, une courbe de Bézier, un cadre aux coins arrondis et en tirets, et un groupe semi-transparent découpé par un chemin de découpage : il s'agit de graphiques vectoriels de la page.
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 });Images et SVG
Une image PNG avec transparence (dessinée dans un canevas directement dans l'exemple), placée deux fois à partir d'une même image enregistrée une seule fois, et un SVG avec un dégradé dessiné en graphique vectoriel — zoomez pour voir qu'il reste net.
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 });Tableaux
Un tableau de 80 lignes : les lignes se poursuivent sur trois pages et la ligne d'en-tête colorée est répétée sur chacune. Faites défiler les pages ou cliquez sur une miniature.
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 });En-tête, pied de page et filigrane
Le titre dans l'en-tête, « Page n of m » dans le pied de page et un filigrane DRAFT sur chaque page ; ils sont dessinés sur les trois pages.
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 });Liens, signets et métadonnées
Des signets, dont un imbriqué, dans le panneau latéral (cliquez sur un signet pour ouvrir sa page) et un lien sur la page 1 qui mène à la page 3. Le titre des métadonnées sert de nom au document.
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 });Enregistrement
Les boutons enregistrent le même document de différentes façons : en téléchargement, dans un fichier sans compression et en indiquant sa taille en octets. La visionneuse montre ce qui est enregistré.
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 });Instantanés JSON et fusion
Le document est enregistré en JSON, restauré à partir de ce JSON, puis les deux versions sont fusionnées en un document de quatre pages (les miniatures les montrent).
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 });Polices
Polices standard
Les polices PDF standard que tout lecteur PDF possède : Helvetica, Times et Courier en gras et en italique, Symbol et ZapfDingbats ; du texte latin et cyrillique sur une même ligne. Aucun fichier de police n'est chargé.
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 vers PDF
Une chaîne HTML avec son CSS mis en page par la bibliothèque : un titre mis en forme, un lien, un tableau avec bordures, une liste et le pied de page. Puis une seconde partie est ajoutée sur une nouvelle page.
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 });Composants VibeFox JS dans un PDF
Un graphique de VibeFox JS Charts (au-dessus de la visionneuse) dessiné dans le PDF en graphique vectoriel, une fois sur toute la largeur et deux fois dans une grille de deux colonnes. Zoomez : les barres et les textes restent nets.
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 });Ouverture et modification des fichiers PDF
Un fichier PDF (ici créé dans le code et enregistré en octets) est ouvert, reçoit un texte APPROVED et un filigrane COPY, puis est enregistré sous forme de mise à jour incrémentale. La zone montre ce que le lecteur a trouvé dans le fichier.
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 });Opérations sur les pages
Deux pages d'un document dessinées côte à côte sur une feuille paysage, suivies des pages de la source, une fois celle-ci tournée, réordonnée et réduite.
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 });Visionneuse
La visionneuse avec sa barre d'outils : miniatures, champ de page, précédente / suivante, zoom, ajustement à la largeur, rotation, recherche, impression et téléchargement. Elle montre le style classic, la deuxième page et une vue pivotée.
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)
});Navigation et zoom
Les boutons appellent les méthodes de la visionneuse : pages, zoom, ajustement, rotation et disposition à une page. La zone montre l'état après chaque étape.
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' })],
]);Panneau latéral : miniatures, signets, calques, signatures
Le panneau latéral avec les signets du rapport sous forme d'arborescence ; les boutons le basculent en miniatures ou le ferment. Cliquez sur un signet ou une miniature pour ouvrir sa page.
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()],
]);Un plan d'étage à trois calques (contenu facultatif, comme ceux des logiciels de CAO ou de PAO). Désactivez et réactivez les calques dans l'onglet Layers ou avec le bouton.
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); }]]);Sélection du texte et recherche
Le mot « invoice » est trouvé et mis en évidence (l'occurrence en cours dans une couleur plus forte) ; Next passe à l'occurrence suivante. Sélectionnez du texte à la souris et copiez-le, ou appuyez sur Ctrl+F dans la visionneuse.
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(''); }],
]);Édition des pages
Le panneau des miniatures avec la barre d'outils des pages : sélectionnez des miniatures (Ctrl / Shift + clic), faites-les glisser vers un autre emplacement, faites-les pivoter ou supprimez-les, annulez l'action. Les boutons font la même chose depuis le code.
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()],
]);Impression
Le bouton d'impression de la barre d'outils ou Print pages 1–2 ouvre la boîte de dialogue d'impression du navigateur avec les pages dessinées à 200 dpi ; la zone montre la progression.
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');
}]]);Dessin d'une page sans visionneuse
Chaque page du rapport dessinée dans son propre canevas à demi-taille, sans le composant de visionneuse.
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' });
}Rendu des fichiers PDF
L'option renderer et pdf.js
Un fichier PDF ouvert, dessiné par le moteur de rendu propre à la bibliothèque (renderer: 'lite') : formes vectorielles, texte dans les polices standard et une image transparente ; pdf.js n'est pas utilisé.
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 });Fonctions de bas niveau
Une page d'un fichier ouvert, peinte dans un canevas avec renderPageLite ; les éléments de texte renvoyés sont encadrés en rouge à leurs positions.
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);
}Extraction et recherche de texte
Le texte du rapport lu par la bibliothèque ; les montants trouvés par une expression régulière et l'adresse e-mail trouvée par le motif prêt à l'emploi sont marqués par des annotations de surlignage dans la visionneuse.
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 });Annotations
À partir du code
Un surlignage, une icône de note, un cadre rouge, une flèche, une zone de texte et un tampon APPROVED ajoutés depuis le code ; ils sont enregistrés comme de vraies annotations 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 });Échange et aplatissement
Les annotations d'un document exporté au format XFDF (dans la zone), importées dans une copie et aplaties à cet endroit : sur la page concernée, elles font partie du contenu de la page et ne peuvent plus être modifiées.
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' });Dans la visionneuse
La barre d'outils des annotations : choisissez l'outil de surlignage et celui de sélection de texte, dessinez à l'encre, faites glisser un cadre ou une flèche, cliquez pour placer une note, ou choisissez un tampon ; sélectionnez une annotation pour la déplacer, la redimensionner ou la supprimer. La zone liste ce qui a été ajouté.
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()],
]);Signatures visuelles
Une signature dessinée avec la date et une signature saisie dans une police cursive du système. Sign ouvre la boîte de dialogue de signature (Draw, Type, Image), puis cliquez sur la page pour y placer la signature.
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()]]);Formulaires
Création des champs
Un formulaire remplissable créé dans le code : champs de texte avec formats numérique et e-mail, case à cocher, boutons radio, liste déroulante (combo box), liste, champ de signature et boutons. Remplissez-le directement ici.
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 });Remplissage et lecture
Le formulaire est rempli depuis le code ; la zone montre les valeurs relues, le résultat de la vérification et les données exportées au format XFDF. Reset amount et Fill again modifient aussi les champs dans la visionneuse.
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 });Remplissage dans la visionneuse
Saisissez du texte dans les champs : chaque modification est écrite dans la zone. Send n'envoie jamais rien : il vérifie le formulaire, signale le champ obligatoire resté vide et transmet les valeurs à votre code.
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('; ')));Caviardage
L'adresse e-mail et le numéro de téléphone sont marqués pour caviardage (cadres rouges, listés dans le panneau). Cliquez sur Apply redactions : le texte sous les marques est supprimé du fichier et des cadres noirs sont dessinés ; puis recherchez l'adresse : elle n'y figure plus.
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');
}]]);Comparaison de documents
Vue de comparaison
Deux versions d'un contrat côte à côte, défilant ensemble : les mots supprimés sont marqués sur l'ancienne, les mots insérés sur la nouvelle, et la liste des modifications. Next change et Overlay appellent les méthodes.
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')],
]);Signatures numériques
Signature
Un contrat signé dans le navigateur avec WebCrypto et un certificat de test écrit dans le code ; le fichier signé est ouvert dans la visionneuse, qui vérifie la signature et l'affiche dans la ligne d'état et dans l'onglet 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()]]);Validation
Le contrat signé est vérifié avec la racine de test comme racine de confiance (valide) et sans aucune racine de confiance (signataire inconnu) ; puis du texte est ajouté à la page après la signature, et la visionneuse montre ce que dit la vérification de cette version dans sa ligne d'état et dans l'onglet 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 });Chiffrement et autorisations
Un document enregistré avec un chiffrement AES-256, qui s'ouvre sans mot de passe mais n'autorise ni l'impression ni la copie : la visionneuse l'ouvre, et son bouton d'impression est désactivé. La zone montre les autorisations lues dans le fichier.
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 et PDF balisé
Structure
Un document balisé : un titre, des paragraphes, une liste, une figure avec texte alternatif et un tableau ; la zone montre l'arborescence de structure que lisent les lecteurs d'écran.
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 });Contrôles et conversion
Les contrôles intégrés s'exécutent sur un document simple : les erreurs PDF/A-2b et PDF/UA avec les clauses des normes, puis une conversion en PDF/A avec ce qui a été corrigé et ce qui n'a pas pu l'être (les polices standard ne sont pas intégrées ; pour cela, fournissez votre propre fichier de police).
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));Modèles et concepteur
Modèles
Un modèle de facture avec des espaces réservés, des expressions et des filtres, un code QR et un code-barres EAN-13, rempli de données ; le tableau fait la somme de ses lignes dans le pied de page. La ligne de commentaire est un champ remplissable.
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 });Concepteur
Le concepteur de modèles avec les données d'aperçu : faites glisser des éléments depuis la palette vers la page, sélectionnez-les, déplacez-les et redimensionnez-les avec accrochage, modifiez leurs propriétés dans le panneau latéral, annulez et rétablissez.
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' });Thèmes et styles
Thèmes
Choisissez un thème dans la liste : les thèmes intégrés light, dark et high-contrast, l'ensemble de thèmes de vibefox-js-themes.css et un thème personnel « brand » enregistré avec registerTheme.
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));Variables CSS
La visionneuse avec quelques variables --vfjs-pdf-* définies sur son élément : barre d'outils sombre avec boutons sombres, espace de travail gris, écarts plus larges entre les pages sans ombre et un accent sarcelle.
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 });Styles prêts à l'emploi
Les aspects prêts à l'emploi de la visionneuse : choisissez classic, dark, minimal, compact ou paper dans la liste.
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));Densité et taille
La densité du conteneur modifie les hauteurs et les marges de la barre d'outils et du panneau latéral ; choisissez compact, normal ou 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; });Localisation et RTL
Langues
La visionneuse en russe, avec le fichier de langue vibefox-js-pdf.ru.js chargé après la bibliothèque ; l'anglais est intégré. Changez de langue avec la liste. Les textes du PDF lui-même ne changent pas.
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 }));Ajout d'une langue
Un dictionnaire allemand partiel ajouté avec addLocale : les boutons de zoom et de téléchargement sont en allemand, les clés qu'il ne contient pas reviennent à l'anglais. Survolez les boutons pour voir les info-bulles.
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' });Droite à gauche (RTL)
La visionneuse est disposée de droite à gauche : la barre d'outils et le panneau latéral sont inversés, et les boutons précédente / suivante indiquent le sens de lecture ; les pages gardent leur géométrie.
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 });Utilisation avec d'autres bibliothèques VibeFox JS
Liaison des composants avec link()
Deux visionneuses liées avec link() : tournez les pages de celle de gauche, et celle de droite suit.
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);