VibeFox JS PDF — Demo
Inicio rápido
HTML puro
El documento de este inicio rápido, creado en el navegador y mostrado de inmediato en el visor con las miniaturas de las páginas; la línea añadida después de crear el visor aparece automáticamente. Save PDF descarga el archivo.
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.');Abrir un archivo PDF
Elija cualquier archivo PDF de su equipo: lo abre y lo dibuja la propia biblioteca, y no se sube nada. Hasta entonces el visor muestra un archivo creado en el código.
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
};Conceptos básicos
Documentos y páginas
Texto que fluye desde el margen superior y un recuadro colocado en coordenadas exactas de la página (en puntos, desde la esquina superior izquierda). La línea bajo el visor muestra el número de páginas y el cursor de flujo.
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 });Eventos
Cada evento del visor y del documento se escribe en el cuadro. Pase páginas, amplíe o pulse Add text: el documento emite change y el visor lo vuelve a dibujar.
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' })],
]);Instantáneas del estado
Cambie la página, el zoom o la rotación, pulse Save state, vuelva a cambiarlos y luego pulse Restore state: el visor vuelve a la vista guardada.
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); }],
]);Creación de documentos
Páginas y flujo
Un libro A5 en Times: un párrafo justificado que pasa automáticamente a las páginas siguientes y, después, una página A4 apaisada y ancha en la que el flujo continúa en la coordenada 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 });Texto
Texto en un recuadro alineado a la derecha, una línea bajo él, en el borde inferior medido del recuadro, y un texto de sello girado y semitransparente.
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 });Formas y trazados
Un círculo, un triángulo, una curva de Bézier, un recuadro redondeado con línea discontinua y un grupo semitransparente recortado por un trazado de recorte: todos ellos son gráficos vectoriales de la página.
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 });Imágenes y SVG
Un PNG con transparencia (dibujado en un canvas directamente en el ejemplo), colocado dos veces a partir de una misma imagen registrada, y un SVG con un degradado dibujado como gráficos vectoriales; amplíe para comprobar que se mantiene nítido.
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 });Tablas
Una tabla de 80 filas: las filas continúan en tres páginas y la fila de encabezado de color se repite en cada una. Desplace las páginas o haga clic en una miniatura.
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 });Encabezado, pie de página y marca de agua
El título en el encabezado, "Page n of m" en el pie de página y una marca de agua DRAFT que cruza todas las páginas; se dibujan en las tres páginas.
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 });Enlaces, marcadores y metadatos
Marcadores con uno anidado en el panel lateral (haga clic en uno para abrir su página) y un enlace en la página 1 que lleva a la página 3. El título de los metadatos se usa como nombre del documento.
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 });Guardado
Los botones guardan el mismo documento de distintas formas: una descarga, un archivo sin compresión y el tamaño en bytes. El visor muestra lo que se guarda.
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 });Instantáneas JSON y combinación
El documento se guarda como JSON, se restaura a partir de él y ambos se combinan en un solo documento de cuatro páginas (las miniaturas los muestran).
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 });Fuentes
Fuentes estándar
Las fuentes estándar de PDF que tiene cualquier lector: Helvetica, Times y Courier en negrita y cursiva, Symbol y ZapfDingbats; texto latino y cirílico en una misma línea. No se carga ningún archivo de fuente.
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 a PDF
Una cadena HTML con su CSS maquetada por la biblioteca: un título con estilo, un enlace, una tabla con bordes, una lista y el pie de página. Después se añade una segunda parte en una página nueva.
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 });Componentes de VibeFox JS en un PDF
Un gráfico de VibeFox JS Charts (encima del visor) dibujado en el PDF como gráficos vectoriales: una vez a todo el ancho y dos veces en una cuadrícula de dos columnas. Amplíe: las barras y los textos se mantienen nítidos.
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 });Apertura y modificación de archivos PDF
Se abre un archivo PDF (aquí creado en el código y guardado como bytes), se le añaden un texto APPROVED y una marca de agua COPY, y se guarda como actualización incremental. El cuadro muestra lo que el lector encontró en el archivo.
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 });Operaciones con páginas
Dos páginas de un documento dibujadas una junto a otra en una hoja apaisada, seguidas de las páginas del archivo de origen tras girarlas, reordenarlas y acortarlas.
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 });Visor
El visor con su barra de herramientas: miniaturas, campo de página, anterior / siguiente, zoom, ajustar al ancho, rotación, búsqueda, imprimir y descargar. Muestra el estilo classic, la segunda página y una vista girada.
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)
});Navegación y zoom
Los botones llaman a los métodos del visor: páginas, zoom, ajuste, rotación y la disposición de una sola página. El cuadro muestra el estado después de cada paso.
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' })],
]);Panel lateral: miniaturas, marcadores, capas, firmas
El panel lateral con los marcadores del informe en forma de árbol; los botones lo cambian a miniaturas o lo cierran. Haga clic en un marcador o en una miniatura para abrir su página.
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 plano de planta con tres capas (contenido opcional, como el que generan los programas de CAD o de autoedición). Active y desactive las capas en la pestaña Layers o con el botón.
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); }]]);Selección de texto y búsqueda
La palabra "invoice" se encuentra y se resalta (la coincidencia actual, en un color más intenso); Next pasa a la siguiente coincidencia. Seleccione el texto con el ratón y cópielo, o pulse Ctrl+F en el visor.
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(''); }],
]);Edición de páginas
El panel de miniaturas con la barra de herramientas de páginas: seleccione miniaturas (Ctrl / Shift + clic), arrástrelas a un nuevo lugar, gírelas o elimínelas, y deshaga los cambios. Los botones hacen lo mismo desde el código.
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()],
]);Impresión
El botón de impresión de la barra de herramientas o Print pages 1–2 abre el diálogo de impresión del navegador con las páginas dibujadas a 200 dpi; el cuadro muestra el progreso.
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');
}]]);Dibujo de una página sin el visor
Cada página del informe dibujada en su propio canvas a la mitad de tamaño, sin el componente visor.
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' });
}Renderizado de archivos PDF
La opción renderer y pdf.js
Un archivo PDF abierto, dibujado con el propio renderizador de la biblioteca (renderer: 'lite'): formas vectoriales, texto en las fuentes estándar y una imagen con transparencia; pdf.js no se utiliza.
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 });Funciones de bajo nivel
Una página de un archivo abierto pintada en un canvas con renderPageLite; los elementos de texto que devolvió se dibujan con contorno rojo en sus posiciones.
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);
}Extracción y búsqueda de texto
El texto del informe leído por la biblioteca; los importes encontrados con una expresión regular y el correo electrónico encontrado con el patrón predefinido se marcan con anotaciones de resaltado en el visor.
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 });Anotaciones
Desde el código
Un resaltado, un icono de nota, un recuadro rojo, una flecha, un cuadro de texto y un sello APPROVED añadidos desde el código; se guardan como anotaciones PDF reales.
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 });Intercambio y aplanado
Las anotaciones de un documento exportadas como XFDF (en el cuadro), importadas en una copia y aplanadas allí: en la página correspondiente forman parte del contenido de la página y ya no se pueden editar.
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' });En el visor
La barra de herramientas de anotaciones: elija resaltar y seleccione texto, dibuje a mano alzada, arrastre un recuadro o una flecha, haga clic para colocar una nota o elija un sello; seleccione una anotación para moverla, cambiarle el tamaño o eliminarla. El cuadro muestra lo que se ha añadido.
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()],
]);Firmas visuales
Una firma dibujada con la fecha y una escrita con el teclado con una fuente cursiva del sistema. Sign abre el diálogo de firma (Draw, Type, Image) y después haga clic en la página para colocar la firma.
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()]]);Formularios
Creación de campos
Un formulario rellenable creado en el código: campos de texto con formatos de número y de correo electrónico, una casilla de verificación, botones de opción, un cuadro combinado, una lista, un campo de firma y botones. Rellénelo aquí mismo.
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 });Relleno y lectura
El formulario se rellena desde el código; el cuadro muestra los valores leídos, el resultado de la comprobación y los datos exportados como XFDF. Reset amount y Fill again también cambian los campos en el visor.
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 });Relleno en el visor
Escriba en los campos: cada cambio se escribe en el cuadro. Send nunca envía nada: comprueba el formulario, marca el campo obligatorio vacío y entrega los valores a su código.
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('; ')));Redacción
La dirección de correo electrónico y el número de teléfono están marcados para redacción (recuadros rojos, enumerados en el panel). Pulse Apply redactions: el texto bajo las marcas se elimina del archivo y se dibujan recuadros negros; después busque la dirección: ya no está.
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');
}]]);Comparación de documentos
Vista de comparación
Dos versiones de un contrato, una junto a otra y con el desplazamiento sincronizado: las palabras eliminadas se marcan en la versión antigua, las insertadas en la nueva, y aparece la lista de cambios. Next change y Overlay llaman a los métodos.
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')],
]);Firmas digitales
Firma
Un contrato firmado en el navegador con WebCrypto y un certificado de prueba escrito en el código; el archivo firmado se abre en el visor, que comprueba la firma y la muestra en la línea de estado y en la pestaña 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()]]);Validación
Se comprueba el contrato firmado con la raíz de prueba como de confianza (válido) y sin ninguna raíz de confianza (firmante desconocido); después se añade texto a la página tras la firma, y el visor muestra en su línea de estado y en la pestaña Signatures lo que dice la comprobación sobre esa versión.
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 });Cifrado y permisos
Un documento guardado con cifrado AES-256 que se abre sin contraseña, pero no permite imprimir ni copiar: el visor lo abre y su botón de impresión está deshabilitado. El cuadro muestra los permisos leídos del archivo.
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 y PDF etiquetado
Estructura
Un documento etiquetado: un título, párrafos, una lista, una figura con texto alternativo y una tabla; el cuadro muestra el árbol de estructura que usan los lectores de pantalla.
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 });Comprobaciones y conversión
Las comprobaciones integradas se ejecutan sobre un documento sencillo: los errores de PDF/A-2b y PDF/UA con las cláusulas de las normas, y después una conversión a PDF/A con lo que corrigió y lo que no pudo corregir (las fuentes estándar no se incrustan; para eso proporcione un archivo de fuente propio).
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));Plantillas y diseñador
Plantillas
Una plantilla de factura con marcadores de posición, expresiones y filtros, un código QR y un código de barras EAN-13, rellenada con datos; la tabla suma sus filas en el pie de página. La línea de comentario es un campo rellenable.
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 });Diseñador
El diseñador de plantillas con los datos de vista previa: arrastre elementos desde la paleta a la página, selecciónelos, muévalos y cambie su tamaño con ajuste automático, edite sus propiedades en el panel lateral, y deshaga y rehaga los cambios.
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' });Temas y estilos
Temas
Elija un tema de la lista: los temas integrados light, dark y high-contrast, el paquete de temas de vibefox-js-themes.css y un tema propio "brand" registrado con 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
El visor con algunas variables --vfjs-pdf-* definidas en su elemento: una barra de herramientas oscura con botones oscuros, un espacio de trabajo gris, separaciones más anchas entre las páginas sin sombra y un acento verde azulado.
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 });Estilos listos para usar
Los estilos listos para usar del visor: elija classic, dark, minimal, compact o paper en la lista.
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));Densidad y tamaño
La densidad del contenedor cambia las alturas y los espaciados interiores de la barra de herramientas y del panel lateral; elija compact, normal o 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; });Localización y RTL
Idiomas
El visor en ruso, con el paquete de idioma vibefox-js-pdf.ru.js cargado después de la biblioteca; el inglés viene integrado. Cámbielo con la lista. Los textos del propio PDF no cambian.
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 }));Añadir un idioma
Un diccionario parcial en alemán añadido con addLocale: los botones de zoom y descarga están en alemán, y las claves que no tiene se muestran en inglés. Pase el cursor sobre los botones para ver los tooltips.
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' });Derecha a izquierda (RTL)
El visor con disposición de derecha a izquierda: la barra de herramientas y el panel lateral se reflejan, y los botones anterior / siguiente siguen la dirección de lectura; las páginas conservan su geometría.
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 });Uso con otras bibliotecas de VibeFox JS
Conexión de componentes con link()
Dos visores conectados con link(): pase páginas en el de la izquierda y el de la derecha lo seguirá.
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);