VibeFox JS PDF — 帮助
概述
VibeFox JS PDF 用于在浏览器和 Node 中创建、打开、查看、编辑、签名和检查 PDF 文件。它可以从零开始生成真正的 PDF 文件(文本、自有字体、图像、以矢量形式输出的 SVG、表格、HTML、表单),也可以打开现有文件并进行修改;其查看器使用自带的渲染器显示任意 PDF 文件,支持搜索、缩略图、注释、表单填写、页面编辑和脱敏。数字签名、加密、PDF/A 与 PDF/UA、文档比较以及所见即所得的模板设计器同样属于这一产品。它是没有依赖的纯 JavaScript 库,可与框架配合使用,也可以不使用框架。
文档是通过方法构建的对象,使用 new PdfDocument(options) 创建,并通过 toBytes() 或 save() 保存;这一过程无需 DOM。组件(查看器 createPdfViewer(target, options)、设计器 createPdfDesigner 和比较视图 createPdfCompare)通过与所有 VibeFox JS 库相同的方法进行控制:setOptions、on、getState、setState、setTheme、destroy。
主要功能
- 文档:任意尺寸的页面、带自动分页的流式文本、绝对定位、形状与路径、JPEG 和 PNG(支持透明度)、以矢量形式绘制的 SVG、跨页重复表头的表格、带页码的页眉和页脚、水印、书签、链接、元数据、JSON 快照。
- 字体:14 种标准 PDF 字体(拉丁文和西里尔文),以及自有的 .ttf、.otf 和 .woff 文件;以子集形式嵌入,支持字距调整、备用字体链和完整的 Unicode。
- HTML 转 PDF:支持 CSS 层叠、表格、列表、图像和链接;根据标题生成书签;表单控件转换为 PDF 字段。
- 来自其他 VibeFox JS 库的图表、表格、示意图、甘特图和文档,只需一行代码即可以矢量图形形式嵌入。
- 已有文件:可以打开(包括损坏和加密的文件),在页面上绘制,插入、删除、移动、旋转、复制、提取、拆分和合并页面;增量保存会保留原始字节。
- 查看器:由库自身的渲染器绘制任意 PDF 文件(无需其他库),可连续滚动数千页,支持缩放、旋转、缩略图、书签、图层、可选择的文本层和搜索,支持拖放页面编辑,并提供现成样式。
- 注释(高亮、下划线、墨迹、形状、带回复的便签注释、文本框、图章)以真正的 PDF 注释形式保存;另有可视签名、拼合,以及 JSON 和 XFDF 数据交换。
- 表单:文本字段、复选框、单选按钮、列表框、签名域和按钮;可填写任意文件的表单,支持验证,支持 FDF / XFDF / JSON 数据,并可在查看器中填写。
- 脱敏:永久删除内容(文本、矢量图形、图像像素);支持文本搜索与提取;两个文档的比较,并提供并排视图。
- 数字签名(PAdES、PKCS#7),使用 WebCrypto 密钥或 .p12 文件;时间戳、验证和长期验证数据;AES 加密和权限;PDF/A-2 / -3、PDF/UA-1 以及带有检查和转换功能的标记 PDF。
- 模板:支持数据占位符、跨页表格和条形码(QR、Data Matrix、Code 128、EAN 等),可在浏览器或 Node 中渲染;并提供用于编辑模板的可视化设计器。
环境要求
- 组件(查看器、设计器、比较视图)需要较新版本的 Web 浏览器。
- 无运行时依赖。库本身不发起任何网络请求:传入的 URL(PDF 文件、图像、字体)只在需要时通过
fetch加载;时间戳和吊销请求通过自定义回调发送。 - Node.js:ES 模块可在 Node 中导入(导入时不接触 DOM)。创建文档、
loadPdf、将 HTML 字符串转换为 PDF、模板、文本提取、脱敏、文本比较、PDF/A 转换和检查均可在 Node 中运行;save()会写入文件。数字签名、AES-256 加密和打开 AES-256 文件需要crypto.subtle(Node 19 及更高版本;在浏览器中需要安全页面:https或localhost)。 - 可选:pdf.js。库使用自身的渲染器绘制 PDF 文件;如果希望使用 pdf.js 显示已加载文件的原始内容,请连接自己的副本(参见 渲染 PDF 文件)。库文件中从不包含它。
安装
库文件
VibeFox JS PDF 是一个独立产品,拥有自己的文件。库的全部 JavaScript 代码为一个文件,样式为一个 CSS 文件:页面只需要这两个文件,其余文件均为可选。
| 文件 | 说明 |
|---|---|
vibefox-js-pdf.global.js | 用于经典 <script> 标签的库文件;定义一个全局变量 VibeFoxJSPdf。压缩版:vibefox-js-pdf.global.min.js。 |
vibefox-js-pdf.esm.js | 相同代码的 ES 模块。压缩版:vibefox-js-pdf.esm.min.js。 |
vibefox-js-pdf.css | 库的全部样式,位于 @layer vfjs 中;包括主题 light、dark 和 high-contrast。压缩版:vibefox-js-pdf.min.css。 |
vibefox-js-themes.css | 可选的主题包:18 个现成主题(参见 主题与样式)。压缩版:vibefox-js-themes.min.css。 |
locales/vibefox-js-pdf.<lang>.js | 可选的语言文件,除英语外每种语言一个(参见 本地化与 RTL)。同一语言的 ES 模块:.esm.js;纯字符串形式:.json。 |
vibefox-js-pdf.d.ts | TypeScript 声明文件(另有 vibefox-js-pdf.esm.d.ts)。 |
*.js.map | 源映射。 |
vibefox-js-pdf-react.js, vibefox-js-pdf-vue.js, vibefox-js-pdf-svelte.js, vibefox-js-pdf-jquery.js | 可选的框架封装包(每个都附带其 .d.ts)。 |
vibefox-js-pdf-angular | 可选的 Angular 包(Angular Package Format)。 |
vibefox-js-pdf-wc.js | 可选的 Web Components 封装包(自定义元素)。 |
Script 标签
引入 CSS 文件和脚本。全局变量 VibeFoxJSPdf 包含库的全部导出内容。从磁盘打开的文件(file://)同样可以使用。
<link rel="stylesheet" href="vibefox-js-pdf.css">
<script src="vibefox-js-pdf.global.js"></script>
<script>
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: doc });
</script>
ES 模块
导入 ES 模块文件并引入 CSS 文件。浏览器只通过 http(s) 加载模块,不能从 file:// 加载。
<link rel="stylesheet" href="vibefox-js-pdf.css">
<script type="module">
import { createPdfViewer } from './vibefox-js-pdf.esm.js';
const viewer = createPdfViewer('#app', { document: doc });
</script>
npm
该库同时以名为 @vibefox/js-pdf 的 npm 包形式提供。请从收到的包目录(或其打包的 .tgz 文件)中安装,然后按名称导入。打包工具通过 @vibefox/js-pdf/css 导出获取 CSS。
npm install ./vibefox-js-pdf
import { createPdfViewer } from '@vibefox/js-pdf';
import '@vibefox/js-pdf/css';
包的导出项:@vibefox/js-pdf(ES 模块)、@vibefox/js-pdf/min、@vibefox/js-pdf/global、@vibefox/js-pdf/global.min、@vibefox/js-pdf/css、@vibefox/js-pdf/min.css、@vibefox/js-pdf/themes、@vibefox/js-pdf/themes.min.css、@vibefox/js-pdf/locales/<lang>、@vibefox/js-pdf/locales/<lang>.json。TypeScript 会自动找到声明文件。
框架封装包
封装包是独立的小型文件;库本身无需它们即可工作。每个封装包只需要 VibeFox JS PDF 及其对应的框架(对等依赖)。封装包不会加载 CSS:请自行引入 vibefox-js-pdf.css。
| 框架 | 文件 | npm 包 | 支持的版本 |
|---|---|---|---|
| React | vibefox-js-pdf-react.js | @vibefox/js-pdf-react | React 16.8 及更高版本 |
| Vue 3 | vibefox-js-pdf-vue.js | @vibefox/js-pdf-vue | Vue 3.3 及更高版本 |
| Angular | vibefox-js-pdf-angular | @vibefox/js-pdf-angular | Angular 17 及更高版本 |
| Svelte | vibefox-js-pdf-svelte.js | @vibefox/js-pdf-svelte | Svelte 3、4 和 5 |
| jQuery | vibefox-js-pdf-jquery.js | @vibefox/js-pdf-jquery | jQuery 1.12 至 4.x |
| Web Components | vibefox-js-pdf-wc.js | @vibefox/js-pdf-wc | 无需框架 |
ES 模块封装包将库作为 @vibefox/js-pdf 导入。若不使用 npm,请在打包工具配置或 import map 中将该名称映射到 vibefox-js-pdf.esm.js。jQuery 封装包从全局变量 VibeFoxJSPdf 获取库。
所有封装包的通用规则:props / inputs 即库的选项(更改的选项传给 setData 或一次 setOptions 调用);事件为框架事件,其负载对象与 on() 相同;每个方法都可通过实例调用;在服务端(SSR)渲染时只输出空容器,实例仅在浏览器中创建。选项 style(现成外观)在 React、Vue、Svelte 和 Angular 中对应的 prop 为 variant,因为 style 以及 className / class 属于宿主元素。
Web Components
在库文件之后加载 vibefox-js-pdf-wc.js。它会基于全局变量 VibeFoxJSPdf 定义元素 <vfjs-pdf-viewer>、<vfjs-pdf-designer> 和 <vfjs-pdf-compare>。特性(attributes)即 kebab-case 格式的选项(对象和数组使用 JSON),属性(properties)同样对应选项,组件的方法即元素的方法;事件为 CustomEvent,名称为 vfjspdfviewer:<event>(设计器为 vfjspdfdesigner:<event>,比较视图为 vfjspdfcompare:<event>),负载位于 detail 中。该元素使用 light DOM,因此库的 CSS 与页面自身的 CSS 照常生效。
<link rel="stylesheet" href="vibefox-js-pdf.css">
<script src="vibefox-js-pdf.global.js"></script>
<script type="module" src="vibefox-js-pdf-wc.js"></script>
<vfjs-pdf-viewer id="v" style="height: 600px" sidebar="thumbnails"></vfjs-pdf-viewer>
<script>
const el = document.getElementById('v');
const doc = new VibeFoxJSPdf.PdfDocument();
doc.text('Hello from a Web Component');
el.document = doc;
el.addEventListener('vfjspdfviewer:pageChange', (e) => console.log(e.detail.page));
</script>
使用打包工具时:import * as lib from '@vibefox/js-pdf'; import { define } from '@vibefox/js-pdf-wc'; define(lib);
快速开始
纯 HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="vibefox-js-pdf.css">
<script src="vibefox-js-pdf.global.js"></script>
</head>
<body>
<button id="save">Save PDF</button>
<div id="preview" style="height: 600px"></div>
<script>
const doc = new VibeFoxJSPdf.PdfDocument({
format: 'A4',
metadata: { title: 'Sales report' },
footer: '{page} / {pages}',
});
doc.text('Sales report', { size: 22, bold: true });
doc.text('The table lists the orders of the month.', { marginBottom: 12 });
doc.table({
columns: [
{ header: 'Item', field: 'item' },
{ header: 'Price', field: 'price', width: 80, align: 'right', format: (v) => v.toFixed(2) },
],
rows: [{ item: 'Widget', price: 990 }, { item: 'Gadget', price: 1490 }],
zebra: '#f4f6f8',
});
// the viewer shows the document before it is saved and follows every change
const viewer = VibeFoxJSPdf.createPdfViewer('#preview', { document: doc, sidebar: 'thumbnails' });
doc.text('Added later: the preview updates by itself.');
document.getElementById('save').onclick = () => doc.save('report.pdf');
</script>
</body>
</html>
文档无需元素:构建它,然后保存即可。查看器会填满其元素:请为该元素设置高度(未设置时,查看器高度为 400 px,由变量 --vfjs-pdf-min-height 决定)。
打开 PDF 文件
const input = document.createElement('input');
input.type = 'file';
input.accept = 'application/pdf';
input.onchange = async () => {
const pdf = await VibeFoxJSPdf.loadPdf(input.files[0]); // bytes, a Blob / File or a URL
viewer.setDocument(pdf); // drawn by the library itself
};
document.body.append(input);
Node
import { PdfDocument } from '@vibefox/js-pdf';
const doc = new PdfDocument();
doc.text('Hello from Node');
await doc.save('out.pdf'); // Node: writes the file; browser: downloads it
const bytes = await doc.toBytes(); // or the bytes (Uint8Array)
React
import { useMemo, useRef } from 'react';
import { PdfDocument } from '@vibefox/js-pdf';
import { VibeFoxJSPdfViewerReact } from '@vibefox/js-pdf-react';
import '@vibefox/js-pdf/css';
export function Report() {
const viewer = useRef(null); // the VibeFoxJSPdfViewer instance
const doc = useMemo(() => {
const d = new PdfDocument();
d.text('Hello from React', { size: 18 });
return d;
}, []);
return (
<div style={{ height: 600 }}>
<button onClick={() => viewer.current.download()}>Download</button>
<VibeFoxJSPdfViewerReact ref={viewer} document={doc} sidebar="thumbnails" onPageChange={(e) => console.log(e.page)} />
</div>
);
}
该包的其他封装包为 VibeFoxJSPdfDesignerReact 和 VibeFoxJSPdfCompareReact。
Vue 3
<script setup>
import { shallowRef } from 'vue';
import { PdfDocument } from '@vibefox/js-pdf';
import { VibeFoxJSPdfViewerVue } from '@vibefox/js-pdf-vue';
import '@vibefox/js-pdf/css';
const doc = new PdfDocument();
doc.text('Hello from Vue');
const pdf = shallowRef(doc);
</script>
<template>
<VibeFoxJSPdfViewerVue :document="pdf" style="height: 600px" @page-change="(e) => console.log(e.page)" />
</template>
文档应通过 shallowRef 传入:查看器直接使用文档对象本身,而不是深层响应式副本。
Angular
import { Component } from '@angular/core';
import { PdfDocument } from '@vibefox/js-pdf';
import { VibeFoxJSPdfViewerComponent } from '@vibefox/js-pdf-angular';
@Component({
selector: 'app-root',
standalone: true,
imports: [VibeFoxJSPdfViewerComponent],
template: `
<vfjs-pdf-viewer-ng #viewer [document]="doc" style="display: block; height: 600px"
(pageChange)="changed($event)"></vfjs-pdf-viewer-ng>
<button (click)="viewer.instance?.download()">Download</button>`,
})
export class AppComponent {
doc = new PdfDocument();
constructor() { this.doc.text('Hello from Angular'); }
changed(e: unknown) { console.log(e); }
}
在 angular.json 的 styles 中或在 index.html 中引入 vibefox-js-pdf.css。对于基于 NgModule 的应用,请导入 VibeFoxJSPdfModule;其他组件为 vfjs-pdf-designer-ng 和 vfjs-pdf-compare-ng。
Svelte
<script>
import { PdfDocument } from '@vibefox/js-pdf';
import { vfjsPdfViewer } from '@vibefox/js-pdf-svelte';
const doc = new PdfDocument();
doc.text('Hello from Svelte');
</script>
<div style="height: 600px" use:vfjsPdfViewer={{ document: doc }}
on:vfjspdfviewer:pageChange={(e) => console.log(e.detail.page)}></div>
jQuery
<script src="jquery.min.js"></script>
<link rel="stylesheet" href="vibefox-js-pdf.css">
<script src="vibefox-js-pdf.global.js"></script>
<script src="vibefox-js-pdf-jquery.js"></script>
<script>
const doc = new VibeFoxJSPdf.PdfDocument();
doc.text('Hello from jQuery');
$('#viewer').vfjsPdfViewer({ document: doc })
.on('vfjspdfviewer:pageChange', (e, payload) => console.log(payload.page));
</script>
核心概念
文档与页面
PdfDocument 是文档模型:包含 pages 列表(PdfPage)、书签(outline)、metadata 和 options。用 loadPdf() 打开的文件与自行构建的文档是同一种对象,每个方法对两者均适用。它不需要 DOM。
- 单位为 PDF 点(pt,1/72 英寸;1 CSS px = 0.75 pt)。坐标原点位于页面左上角,向右和向下增长。A4 页面为 595.28 × 841.89 pt。
- 在文档和页面的方法中页码从 0 开始计数(
doc.page(0)、addAnnotation(0, …)),而在查看器(goToPage(1))和页码范围字符串('1-3, 5')中从 1 开始计数。 - 放置内容的两种方式:流式排版(
doc.text()、doc.table()、doc.image()、doc.addHtml(),从页边距内的光标位置开始,需要时自动添加新页面),以及在页面上的绝对定位(page.text(…, { x, y })、page.drawRect()等)。 - 颜色可以是
'#rgb'、'#rrggbb'或[r, g, b](0–255);null或'none'表示无填充 / 无描边。 - 保存是异步的:
await doc.toBytes()返回Uint8Array;save(filename)、toDataURL()和toBlobURL()都基于它实现。
const report = new VibeFoxJSPdf.PdfDocument({ format: 'A4', orientation: 'portrait', margins: { top: 56, right: 50, bottom: 56, left: 50 } });
report.text('Flowing text starts at the top margin.');
const page = report.currentPage; // the page the flow cursor is on
page.drawRect(50, 120, 200, 60, { fill: '#e0f2fe', stroke: '#0369a1', radius: 6 });
page.text('Placed at x 60, y 140', { x: 60, y: 140, size: 10 });
console.log(report.pageCount, report.cursor); // 1 { page: 0, y: … }
const bytes = await report.toBytes();
组件
查看器、设计器和比较视图都是 VibeFox JS 组件。可以使用工厂函数(createPdfViewer、createPdfDesigner、createPdfCompare)创建组件,也可以对类使用 new(VibeFoxJSPdfViewer、VibeFoxJSPdfDesigner、VibeFoxJSPdfCompare);使用 setOptions 进行更改,使用 destroy() 销毁。目标可以是元素或选择器。
const v = VibeFoxJSPdf.createPdfViewer('#app', { document: doc, zoom: 1.25, sidebar: 'outline' });
v.setOptions({ layout: 'single', toolbar: false });
v.goToPage(2);
v.destroy();
查看器会实时显示文档:它监听文档的 change 事件,因此添加或修改的任何内容都会立即显示,无需等待文件保存。
事件
每个事件处理函数都接收一个负载对象。可以在选项中订阅(on: { pageChange: fn }),也可以之后通过 on、once 和 off 订阅;on('*', (event, payload) => …) 会接收所有事件。文档同样是事件发射器。
viewer.on('pageChange', (e) => console.log(`page ${e.page} of ${e.pages}`));
viewer.on('zoomChange', (e) => console.log(e.zoom));
doc.on('change', (e) => console.log('changed:', e.type));
doc.on('save', (e) => console.log(e.filename, e.size));
每个 VibeFox JS 组件都会触发 ready、optionsChange、themeChange 和 destroy 事件。完整列表参见 API 参考。
状态快照
查看器的 getState() 返回 { page, zoom, style, rotation, sidebar };setState(state) 用于恢复状态(缺失的键保持当前值)。设计器的状态为 { page, zoom, preview, selection, grid, snap, panel },比较视图的状态为 { layout, change, zoom }。
localStorage.setItem('pdf-view', JSON.stringify(viewer.getState()));
viewer.setState(JSON.parse(localStorage.getItem('pdf-view')));
整个文档可通过 doc.toJSON() 保存为 JSON,并通过 PdfDocument.fromJSON(json) 恢复(参见 创建文档)。
创建文档
页面与流式排版
new PdfDocument(options) 创建一个空文档。流式排版方法会自行添加第一页;addPage({ format, orientation, margins }) 添加一个带有自定义尺寸的页面,并将其设为流式排版的当前页面。页面格式包括:ISO A0 至 A10(默认 'A4')、B0 至 B10、信封 C0 至 C10,以及 'DL'、'Letter'、'Legal'、'Tabloid'、'Ledger'(即横向的 Tabloid:请与 orientation: 'landscape' 一起使用,纵向页面会将其变为 Tabloid)、'Executive'、'Statement',或以 pt 为单位的 [width, height]。名称不区分大小写('a6')。未知名称会抛出 RangeError,其 code: 'page-format'(适用于文档选项、addPage、insertPage 和模板)。FORMATS 包含各种尺寸,pageFormatName(name) 返回名称的标准写法(或 null),resolvePageSize(format, orientation) 计算尺寸。
const book = new VibeFoxJSPdf.PdfDocument({ format: 'A5', font: { family: 'times', size: 11 } });
book.text('Chapter 1', { size: 18, bold: true, marginBottom: 8 });
book.text('A long paragraph wraps inside the margins and continues on the next page when the page is full.', { align: 'justify' });
book.moveDown(20); // empty space, pt
book.ensureSpace(120); // a new page unless 120 pt are left
book.addPage({ format: 'a4', orientation: 'landscape' });
console.log(VibeFoxJSPdf.pageFormatName('a6')); // 'A6'
try { book.addPage({ format: 'A11' }); } catch (e) { console.log(e.code); } // 'page-format'
book.setCursorY(200); // continue the flow at y 200 of the current page
book.text('A wide page.');
流式排版方法:text(text, options)、image(src, options)、svg(svg, options)、table(options)、addHtml(html, options)、addComponent(component, options);光标:cursor({ page, y })、currentPage、setCursorY(y)、moveDown(dy)、ensureSpace(h)。页面:pages、pageCount、page(i);每个页面具有 width、height、margins、contentWidth、contentHeight 和 index 属性。
文本
doc.text()(流式排版)和 page.text()(定位放置)的选项:font、size(单位为 pt,默认 12)、bold、italic、color、align('start'(默认值)、'end'、'left'、'center'、'right'、'justify';start 和 end 随段落方向变化)、dir('auto'(默认值)、'ltr'、'rtl';参见 从右到左与复杂文字)、lineHeight(默认 1.35)、opacity、kerning、ligatures;流式排版中还包括 indent、width、paragraphGap、marginBottom;在页面上还包括 x、y、width 和 rotate(角度,仅限单行)。换行符 \n 会开始新段落。page.text() 返回其占用的区域({ x, y, width, height, bottom, lines });page.measureText(text, { font, size, bold, dir }) 用于在不绘制的情况下测量字符串。
const p = doc.page(0);
const box = p.text('Total: 1 250.00 EUR', { x: 350, y: 700, width: 195, align: 'right', size: 14, bold: true });
p.drawLine(350, box.bottom + 4, 545, box.bottom + 4, { color: '#94a3b8', width: 0.5 });
p.text('PAID', { x: 420, y: 760, size: 28, color: '#16a34a', rotate: 15, opacity: 0.6 });
console.log(p.measureText('Total', { size: 14, bold: true })); // width in pt
形状与路径
页面方法包括:drawLine(x1, y1, x2, y2, { color, width, dash, opacity })、drawRect(x, y, w, h, { fill, stroke, lineWidth, dash, opacity, radius })、drawEllipse(cx, cy, rx, ry, style)、drawCircle(cx, cy, r, style)、drawPolygon(points, { close, …style }),以及带有 M、L、C、Q 和 Z 段的 drawPath(segments, style)。group(options, fn)(或 beginGroup / endGroup)可以在带有变换 matrix、剪切路径 clip 和一个 opacity 的情况下绘制页面的一部分;分组可以嵌套。
const pg = doc.page(0);
pg.drawCircle(80, 760, 20, { fill: '#fde68a', stroke: '#b45309', lineWidth: 1.5 });
pg.drawPolygon([[130, 780], [150, 740], [170, 780]], { fill: '#bfdbfe', close: true });
pg.drawPath([{ c: 'M', x: 200, y: 780 }, { c: 'C', x1: 220, y1: 730, x2: 260, y2: 790, x: 280, y: 750 }], { stroke: '#7c3aed', lineWidth: 2 });
pg.group({ opacity: 0.5, clip: [{ c: 'M', x: 300, y: 740 }, { c: 'L', x: 360, y: 740 }, { c: 'L', x: 360, y: 780 }, { c: 'L', x: 300, y: 780 }, { c: 'Z' }] }, (g) => {
g.drawRect(290, 730, 90, 60, { fill: '#ef4444' });
});
图像与 SVG
JPEG 和 PNG(支持所有颜色类型和透明度)可以以字节(Uint8Array、ArrayBuffer)、数据 URL 或 addImage() 返回的 id 形式传入,该函数会注册一次图像,供多处使用。doc.image(src, { width, height, align, opacity }) 将图像放入流式排版并保持其比例;page.drawImage(src, x, y, { width, height }) 在页面上放置图像,并返回其实际尺寸。其他格式(GIF、WebP)无法读取:请先将其绘制到 canvas 中,再传入 PNG。
SVG 以矢量图形而非图片的形式绘制:流式排版中使用 doc.svg(svg, { width, align }),页面上使用 page.drawSvg(svg, x, y, { width, height })。输入可以是 SVG 标记、其字节数据或 <svg> 元素。支持形状、路径、描边和虚线、变换、渐变、剪切路径、标记、<use>、文本(使用已注册的字体)、嵌入的 PNG / JPEG 图像,以及 <style> 中的 CSS;蒙版、滤镜、图案和 <foreignObject> 会被跳过并给出警告(通过 onWarning 处理,否则输出一条控制台警告;文档同时触发 warning 事件)。
const logo = doc.addImage(logoPng); // a PNG data URL, registered once
doc.page(1).drawImage(logo, 50, 60, { width: 48 });
doc.image(logo, { width: 120, align: 'center', marginBottom: 12 });
doc.svg(`<svg xmlns="http://www.w3.org/2000/svg" width="300" height="120">
<defs><linearGradient id="g"><stop offset="0" stop-color="#0ea5e9"/><stop offset="1" stop-color="#6366f1"/></linearGradient></defs>
<rect x="10" y="10" width="280" height="100" rx="12" fill="url(#g)"/>
<text x="150" y="70" text-anchor="middle" font-size="28" fill="#fff">Vector</text>
</svg>`, { width: 240, align: 'center' });
表格
doc.table(options) 在流式排版中排列表格:单元格文本自动换行,行会转到下一页,并在下一页重复表头(repeatHeader,默认 true)。列为 { header, field, width, align, format(value, row) }(width 的单位为 pt,或 'auto');未指定 columns 时,列取自行的键。行可以是对象或数组。样式选项:fontSize、font、color、cellPadding、borderColor、borderWidth、zebra(隔行填充)、headerStyle: { fill, color, bold }、x 和 width。返回 { y, pages, rows }。
const res = doc.table({
columns: [
{ header: 'Item', field: 'item' },
{ header: 'Qty', field: 'qty', width: 50, align: 'right' },
{ header: 'Amount', field: 'amount', width: 90, align: 'right', format: (v) => v.toFixed(2) },
],
rows: Array.from({ length: 80 }, (_, i) => ({ item: `Item ${i + 1}`, qty: i % 5 + 1, amount: (i + 1) * 9.5 })),
zebra: '#f8fafc',
headerStyle: { fill: '#0f766e', color: '#ffffff' },
fontSize: 9,
});
console.log(res.pages, res.rows);
条形码(QR、Data Matrix、Code 128、EAN-13、EAN-8、UPC-A、Code 39、ITF、ITF-14)以及绑定数据的表格是模板的元素(参见 模板与设计器)。
页眉、页脚和水印
选项 header 和 footer(或 setHeader() / setFooter())会在每页的上 / 下页边距中输出一行:可以是包含占位符 {page}、{pages}、{title} 和 {date} 的文本,也可以是 { text, align, size, color, font, bold }。watermark / setWatermark(text, { size, color, opacity, angle, font, bold }) 会在每页上绘制一段横跨页面的文字;传入 null 则移除水印。它们同样适用于已打开文件的页面。
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 });
链接、书签和元数据
const pageOne = doc.page(0);
pageOne.link(50, 100, 200, 16, { url: 'https://example.com/terms' }); // external link
pageOne.link(50, 120, 200, 16, { page: 2, destY: 0 }); // to the third page
const chapter = doc.addBookmark('Terms', { page: 1 });
doc.addBookmark('Payment', { page: 1, y: 300, parent: chapter }); // nested bookmark
doc.setMetadata({ title: 'Invoice 2026-001', author: 'Example Ltd', subject: 'Invoice', keywords: 'invoice, 2026' });
书签位于 doc.outline 中;查看器会在侧边栏中显示它们。
保存
| 方法 | 返回值 | 说明 |
|---|---|---|
toBytes(options) | Promise<Uint8Array> | PDF 文件。选项:compress、incremental(已打开的文件)、encrypt、pdfa、pdfua、tagged,仅对本次输出有效。 |
save(filename) | Promise<Uint8Array> | 浏览器中:下载文件;Node 中:写入文件。触发 save 事件。 |
toDataURL(options) | Promise<string> | data:application/pdf;base64,… 形式的 URL。 |
toBlobURL(options) | Promise<string> | blob: URL(浏览器中),例如用于在新标签页中打开。 |
文件为 PDF 1.7 格式。当平台支持 CompressionStream 时,内容流会被压缩(compress: 'auto',默认值)。
JSON 快照与合并
doc.toJSON() 以 JSON 形式输出整个文档(包括页面及其绘图内容、以 base64 表示的图像和字体、书签、注释和表单字段);PdfDocument.fromJSON(json) 用于恢复文档,适用于存储文档、发送到服务器或稍后再修改的情况。toJSON({ fonts: false }) 会省略字体文件;可通过 fromJSON(json, { fonts: [{ family, data }] }) 将其补回。PdfDocument.merge(a, b, …) 将多个文档(库中创建的文档和已打开的文件)合并为一个文档:页面、图像、字体、书签、表单字段和注释都会随之合并。
const json = JSON.stringify(doc.toJSON());
const copy = VibeFoxJSPdf.PdfDocument.fromJSON(JSON.parse(json));
const both = VibeFoxJSPdf.PdfDocument.merge(doc, copy);
console.log(both.pageCount); // 6
已打开文件的快照只保留通过库添加的绘制内容,不包含原始页面;此类文档应保存为 PDF 字节数据。
字体
库本身不附带字体文件。它内置 14 种标准 PDF 字体(每个 PDF 阅读器都支持),并会嵌入所提供的字体文件。
标准字体
字体族 'helvetica'(默认)、'times' 和 'courier',可使用 bold 和 italic,此外还有 'symbol' 和 'zapfdingbats'。前三种字体的文本支持拉丁文(Windows-1252)和西里尔文(Windows-1251),同一行可以混用两者。'symbol' 包含希腊字母和数学符号,'zapfdingbats' 包含装饰符号(对勾、叉号、带圈数字、箭头等):可以使用 Unicode 字符书写其文本(希腊字母、∑、∞、U+2714 对勾、带圈数字等),也可以使用其编码中的字母代码(a、b、g 即 α、β、γ;4 即对勾)。查看器显示它们的方式与保存的文件一致,文本提取和搜索则返回 Unicode 字符。其他任何字符(CJK、阿拉伯文、希伯来文、₽ 等)都需要自有的字体文件:没有字体文件时,这些字符会被写成 ?。标准字体不会嵌入,因此不能用于 PDF/A(参见 PDF/A、PDF/UA 与标记 PDF)。
自有字体
registerFont(family, bytes, { weight, style, index, kerning }) 用于嵌入 TrueType 或 OpenType 字体(.ttf;带有 TrueType 或 CFF 轮廓的 .otf;.ttc 中的单个字体);await loadFont(family, source, options) 以相同方式从 URL、Blob 或字节数据加载字体,并支持读取 .woff(不支持 WOFF2,请将其转换为 .ttf / .otf / .woff)。文档选项 fonts: [{ family, data, weight, style }] 会一次性注册这些字体。已注册的字体族可在所有位置用作 font 值:流式文本和页面文本、表格、页眉和页脚、水印、SVG 文本、HTML、表单字段和模板。
const intl = new VibeFoxJSPdf.PdfDocument();
await intl.loadFont('Noto Sans', 'fonts/NotoSans-Regular.ttf');
await intl.loadFont('Noto Sans', 'fonts/NotoSans-Bold.ttf', { weight: 700 });
intl.text('Grüße · Привет · Cześć', { font: 'Noto Sans', size: 14 });
intl.text('A bold heading', { font: 'Noto Sans', bold: true });
console.log(intl.getFonts().map((f) => `${f.family} ${f.weight} ${f.style}`), intl.hasFont('Noto Sans'));
- 只写入所使用的字形(子集),并附带 ToUnicode 映射,因此文本可在任何阅读器中被选择、复制和搜索。
- 字体的字距(GPOS 或 kern 表)会被应用和测量;可通过字体上的
kerning: false、文本选项或文档选项font.kerning将其关闭。 bold和italic会选择最接近的已注册字体;如需真正的粗体 / 斜体,请注册粗体 / 斜体字体文件(不使用合成样式)。- 备用字体链:
setFallbackFonts([...families])(或选项fallbackFonts)列出已注册的字体族;对于文本所用字体缺少的字符,会按顺序尝试这些字体,例如拉丁文字体之后的 CJK 字体。请在添加文本之前设置。 - 中文、日文和韩文文本会在字符之间断行,无需空格,并遵循基本的断行规则。
- 字体的标准连字(fi、fl 等)会被应用;可通过文本选项
ligatures: false或文档选项font.ligatures将其关闭。
从右到左与复杂文字
使用自有字体文件的文本,其字形整形与排序方式与浏览器相同:从右到左的文本(阿拉伯文、希伯来文、波斯文、乌尔都文)按照 Unicode 双向算法从右向左排列,其中的数字和拉丁文单词保持原有顺序,阿拉伯字母会连写,天城文(印地文、马拉地文、尼泊尔文)会组合成音节(连写辅音、reph、元音符号),符号和元音标记由字体定位,并应用字体的连字和字距。标准字体不包含阿拉伯文、希伯来文或印度系文字的字母:请注册包含这些字母的字体。
dir:'auto'(默认值,根据每个段落中第一个强方向字母判断)、'ltr'或'rtl',适用于doc.text、page.text、page.measureText、doc.table,也可作为文档选项使用(即文本、表格和模板的默认值)。align: 'start'(默认)在从右到左的段落中对齐到右侧,'end'则对齐到左侧;indent位于右侧;两端对齐段落的最后一行靠右。- 设置
dir: 'rtl'的表格,第一列位于右侧;列的默认align为'start'。 - 文本行按逻辑顺序断行,然后重新排序;单词绝不会在字母簇内部被截断。
- 文件中的文本保持逻辑顺序:从任何阅读器复制、
extractText、搜索和脱敏得到的文本都按阅读顺序排列(对于其他程序生成的文件同样适用)。
const ar = new VibeFoxJSPdf.PdfDocument({ dir: 'rtl' });
await ar.loadFont('Noto Naskh Arabic', 'fonts/NotoNaskhArabic-Regular.ttf');
await ar.loadFont('Noto Sans Hebrew', 'fonts/NotoSansHebrew-Regular.ttf');
ar.text('مرحبا بالعالم — الطلب رقم 42', { font: 'Noto Naskh Arabic', size: 16 }); // right-aligned, joined
ar.text('שלום עולם', { font: 'Noto Sans Hebrew', align: 'end' }); // end = left in RTL
ar.table({ font: 'Noto Naskh Arabic', columns: [{ header: 'المنتج', field: 'p' }, { header: 'الكمية', field: 'q' }], rows: [{ p: 'قلم', q: 3 }] });
同一引擎也用于 HTML 转 PDF、模板以及其他 VibeFox JS 库的 PDF 导出中的文本(使用其嵌入字体)。库文件在加载时即自动启用该引擎。如果构建工具处理可读的 vibefox-js-pdf.esm.js 并移除未使用的代码,则只有当代码中引用了 enableComplexScripts 或 complexScripts 时,该引擎才会保留在构建结果中:请调用一次 VibeFoxJSPdf.enableComplexScripts();否则从右到左的文本将按逻辑顺序写入,并会输出相应警告。
HTML 转 PDF
htmlToPdf(html, options) 根据 HTML 创建新文档;doc.addHtml(html, options) 将 HTML 排入文档的流式排版中(从光标处开始,之后的内容接续其后)。输入可以是 HTML 字符串、其字节数据,或者(在浏览器中)一个实时元素:此时将应用页面的计算样式。库拥有自己的 HTML 解析器和 CSS 层叠机制,因此 HTML 字符串同样可以在 Node 中使用。
const html = `<style>
h1 { color: #0f766e; }
table { border-collapse: collapse; width: 100%; }
td, th { border: 1px solid #cbd5e1; padding: 4px 8px; }
</style>
<h1>Quarterly report</h1>
<p>Revenue grew by <b>12 %</b>. Details: <a href="https://example.com/q3">example.com/q3</a>.</p>
<table><thead><tr><th>Region</th><th>Sales</th></tr></thead>
<tbody><tr><td>North</td><td>120</td></tr><tr><td>South</td><td>98</td></tr></tbody></table>`;
const report = await VibeFoxJSPdf.htmlToPdf(html, {
format: 'A4',
footer: '<p style="text-align: right">{page} / {pages}</p>',
});
const result = await doc.addHtml('<h2>Notes</h2><ul><li>First</li><li>Second</li></ul>', { newPage: true });
console.log(report.pageCount, result.pages, result.warnings);
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
css | string | — | 在 <style> 元素之后添加的 CSS(用于 HTML 字符串)。 |
header, footer | string 或 { html, gap } | — | 本次调用中每页上 / 下页边距内的 HTML;{page} {pages} {title} {date}。 |
bookmarks | boolean 或 number | htmlToPdf:true,addHtml:false | 标题 h1–h6(或至某一级)作为嵌套书签。 |
forms | boolean | true | 输入框、复选框、单选按钮、下拉选择框、文本区域和按钮会成为 PDF 表单字段;false 则按其值进行绘制。 |
fontSize, fontFamily, color | number, string | 12 pt,文档字体 | 根字号(12 pt = 16 CSS px)、字体族和文本颜色。 |
baseUrl | string | — | 相对链接、图像和字体的基准。 |
resolveImage(src) | function | — | 库无法获取的图像的字节数据 / 数据 URL / SVG 标记(Node)。 |
newPage | boolean | false | 从新页面开始。 |
repeatHeader | boolean | true | 在表格的每一页重复 <thead> 行。 |
title | boolean | true | <title> 成为文档标题。 |
locale | string | — | {date} 的语言区域。 |
onWarning(message) | function | 一条控制台警告 | 不支持的 HTML / CSS。 |
支持:具有外边距、内边距、边框(实线、虚线、点线、双线)、圆角、背景色的块级和行内布局;通过 font-family 选择字体(已注册的字体族或标准字体:serif → Times,monospace → Courier,其他 → Helvetica);文本装饰、对齐、缩进、white-space;各种常见编号方式的列表;带有列跨度和行跨度、合并或分离边框、重复表头行的表格;图像(PNG、JPEG、SVG;其他格式在浏览器中通过 canvas 处理);链接(http(s)、mailto、tel、#anchors);通过 break-before、break-after、break-inside: avoid 控制的分页;htmlToPdf 支持 CSS @page { size; margin };支持 TTF / OTF / WOFF 的 @font-face;自定义属性和 calc()。以下内容会以流式排版方式处理,并给出警告:flex 和 grid、浮动、绝对 / 固定定位、变换、阴影、背景图像和渐变、多列、::before / ::after 内容;<link rel="stylesheet"> 不会被加载(请将 CSS 放入 css 选项)。
从右到左:dir 属性(ltr、rtl、auto)和 CSS direction;text-align: start / end(也适用于单元格和列表项);margin、padding 和 border 的 -inline-start / -inline-end(以及 -inline 简写)随元素的方向变化;逻辑属性与物理属性同时出现时,后者生效,与浏览器中的行为一致;从右到左元素中的表格,第一列位于右侧;列表向右缩进,标记位于右侧(包括 outside 和 inside);设置了宽度的块或表格位于右边缘。@page { size } 接受库中的所有页面格式名称。
PDF 中的 VibeFox JS 组件
await doc.addComponent(component, options) 将其他 VibeFox JS 库的组件(图表、表格、示意图、甘特图、编辑器文档、交易图表)以矢量图形的形式绘制到文档中:可以在流式排版中绘制(采用内容宽度和屏幕上的宽高比),也可以放在 { page, x, y, width, height } 指定的位置。它支持组件具有的任何导出形式(其 PDF 绘图、SVG 或自身的 PDF 文件);仅具有图片导出形式的组件会以图像形式放置(kind: 'image')。组件绘制的文本使用本文档中已注册的字体(从右到左的文本,以及阿拉伯文、希伯来文或天城文标签会被整形并排序,参见 从右到左与复杂文字)。VibeFox JS PDF 为此无需其他库,只需传入页面上已存在的组件。
// VibeFox JS Charts is also on the page (its file loaded)
const chart = VibeFoxJSCharts.createChart('#app', { categories: ['A', 'B', 'C'], series: [{ type: 'column', data: [5, 8, 3] }] });
const report = new VibeFoxJSPdf.PdfDocument();
report.text('Sales by product', { size: 16, bold: true, marginBottom: 8 });
const placed = await report.addComponent(chart, { height: 220 });
console.log(placed.kind, placed.via, placed.pageIndex);
await report.addComponents([chart, chart], { columns: 2, gap: 12, height: 160 }); // a layout grid
addComponents(items, { columns, gap, height, marginBottom }) 以网格形式排列多个组件(items 可以是 { component, span, height, options });addPageFrom(component) 会按照本文档的页面尺寸,追加组件自身 PDF 导出的所有页面(例如长表格,或以标题作为书签的文档);每次调用的 options 会传给组件的导出(标题、图例等)。
打开和修改 PDF 文件
await loadPdf(input, options) 用于打开已有的 PDF:输入可以是字节数据、Blob / File、URL 或数据 URL。结果为 PdfDocument,其页面即文件中的页面;构建器的全部功能都可用于这些页面(文本、形状、图像、SVG、字体、链接、表单字段,以及每页的页眉、页脚和水印),还可以添加新页面,并修改元数据。
const pdf = await VibeFoxJSPdf.loadPdf(file); // a File from <input type="file">
console.log(pdf.pageCount, pdf.sourceInfo.version, pdf.metadata.title);
pdf.page(0).text('APPROVED', { x: 400, y: 40, size: 18, bold: true, color: '#16a34a' });
pdf.setWatermark('COPY', { opacity: 0.1 });
pdf.setMetadata({ subject: 'Approved copy' });
const updated = await pdf.toBytes(); // incremental update: the original bytes stay unchanged
const compact = await pdf.toBytes({ incremental: false }); // a new compact file
- 在已打开的页面上绘制时,以页面显示的方式为准(其裁剪框和旋转):(0, 0) 是阅读器中所见的左上角。
- 保存默认写入增量更新:原始字节之后附加所做的更改(未做任何更改时,字节保持不变)。
incremental: false会写入新文件,不包含已删除的页面和旧版本。 - 读取范围:所有交叉引用类型、对象流、更新链、损坏的文件(通过扫描重建;
sourceInfo.repaired),以及文件头之前带有多余数据的文件。 - 加密文件可使用用户密码(通常为空)或所有者密码(
{ password })打开:支持 RC4、AES-128、AES-256。保存时使用相同的加密方式。权限会被报告(sourceInfo.encrypted.allowed),但在处理文档时不会强制执行。 - 已签名文件:
sourceInfo.signed、signatures、certified。增量保存会保留签名(阅读器会列出之后的更改);incremental: false会破坏签名,并会给出警告。
sourceInfo(由库创建的文档为 null):{ version, pageCount, size, xref, updates, repaired, encrypted, signed, certified, signatures, warnings }。loadPdf 的错误带有 code:'not-pdf'、'damaged'、'encrypted'(不受支持的加密方式,例如基于证书的加密)、'password'(缺少密码或密码错误)。
try {
const secret = await VibeFoxJSPdf.loadPdf(pdfBytes, { password: 'secret', onWarning: (m) => console.warn(m) });
console.log(secret.sourceInfo.encrypted);
} catch (e) {
if (e.code === 'password') console.log('Ask the user for the password');
else throw e;
}
parsePdf(bytes) 是一个快速读取器,用于读取简单文件的版本、页数、加密标志和元数据;loadPdf 则是完整的读取器。
页面操作
这些方法既适用于库中创建的文档,也适用于已打开的文件;链接和书签会跟随其指向的页面。
| 方法 | 返回值 | 说明 |
|---|---|---|
insertPage(index, { format, orientation, margins }) | PdfPage | 在 index 处插入一个新的空白页面。 |
removePage(index) | this | 删除页面(触发 pageRemove)。 |
movePage(from, to) | this | 移动页面。 |
rotatePage(index, angle), page.setRotation(angle) | this | 将页面旋转 90° 的倍数(相对 / 绝对);绘图坐标保持不变。 |
copyPages(src, indices, { at }) | PdfPage[] | 复制另一个文档中的页面(或复制本文档中的页面),并保留其图像、字体、链接、字段和注释。 |
extractPages(pages) | PdfDocument | 包含这些页面的新文档(从 0 开始的索引,或范围字符串 '1-3, 7'),并附带其书签和元数据。 |
split(spec) | PdfDocument[] | 多个文档:{ every: n }、{ ranges: '1, 2-5, 6-' } 或 { bookmarks: level }(每个书签对应一个部分,并以书签名称命名)。 |
PdfDocument.merge(...docs) | PdfDocument | 将多个文档合并为一个;同名表单字段会获得 name_2、…后缀。 |
page.drawPage(src, index, x, y, { width, height, align }) | box | 将任意文档中的页面以矢量形式绘制到指定区域(在同一张纸上放置多个页面,即拼版)。 |
const pdf = await VibeFoxJSPdf.loadPdf(pdfBytes);
pdf.rotatePage(0, 90);
pdf.movePage(2, 0);
pdf.removePage(1);
const firstTwo = doc.extractPages('1-2');
const single = doc.split({ every: 1 }); // one document per page
const all = VibeFoxJSPdf.PdfDocument.merge(firstTwo, pdf);
// two pages on one landscape sheet
const sheet = new VibeFoxJSPdf.PdfDocument({ margins: { top: 0, right: 0, bottom: 0, left: 0 } });
const s = sheet.addPage({ orientation: 'landscape' });
s.drawPage(doc, 0, 20, 20, { width: 390, height: 555 });
s.drawPage(doc, 1, 432, 20, { width: 390, height: 555 });
console.log(single.length, all.pageCount);
在查看器中,同样的操作可通过鼠标和键盘完成(参见 查看器 → 页面编辑)。
查看器
createPdfViewer(target, options) 用于显示 PdfDocument,它可以是正在构建的文档(会立即跟随每一次更改),也可以是通过 loadPdf() 打开的文件。setDocument(doc, { page }) 用于显示另一个文档(默认显示第 1 页,或显示指定的 page),getDocument() 返回当前文档,传入 null 时显示 "No document"。工具栏包括侧边栏按钮、页码输入框、上一页 / 下一页、缩小 / 放大、适合宽度、旋转、搜索、打印和下载(toolbar: false 可将其隐藏)。
const v = VibeFoxJSPdf.createPdfViewer('#app', {
document: doc,
page: 2, // opened at page 2 (1-based)
zoom: 1, // 1 = 100 %; minZoom 0.25, maxZoom 4
layout: 'continuous', // every page in one scroll; 'single' = one page at a time
sidebar: 'thumbnails', // 'thumbnails' | 'outline' | 'layers' | 'signatures' | null
filename: 'invoice.pdf', // name of the downloaded file
style: 'classic', // ready-made look (see Theming and styling)
});
v.fitWidth();
v.rotate(90); // turns the view, not the document
console.log(v.getState()); // { page: 2, zoom: …, style: 'classic', rotation: 90, sidebar: 'thumbnails' }
导航与缩放
方法:goToPage(n)(从 1 开始)、nextPage()、prevPage()、setZoom(zoom)、zoomIn()、zoomOut()、fitWidth()、fitPage()、rotate(delta)、setRotation(angle)、getRotation()、refresh()、download();选项 page 在创建查看器时打开该页面(不触发 pageChange 事件),setOptions({ page }) 会像 goToPage 一样翻到该页,setOptions({ document, page }) 会在该页显示另一个文档;事件包括 pageChange、zoomChange、rotationChange、documentChange、renderComplete(每绘制一页触发一次)。在连续布局中,当前页会随滚动变化。只绘制可见页面(以及前后各一页),因此包含数千页的文件也能流畅滚动;在高分辨率屏幕上页面会清晰绘制,深度缩放时则以完整分辨率绘制可见部分。
侧边栏:缩略图、书签、图层、签名
showSidebar(view)、hideSidebar()、toggleSidebar() 以及选项 sidebar 可打开带有标签页的面板(标签页为图标;名称既是工具提示,也是屏幕阅读器读出的名称;变量 --vfjs-pdf-tab-label-display: inline 会在图标旁显示名称,此时标签页会换行):'thumbnails'(按需绘制,并标出当前页)、'outline'(文件的书签以及通过 addBookmark() 添加的书签,以树形显示;单击即可打开对应页面)、'layers'(仅适用于包含可选内容的文件:每个图层一个复选框;锁定图层和单选组按照文件的定义显示)和 'signatures'(仅适用于已签名的文件,参见 数字签名)。事件 sidebarChange。
const layers = viewer.getLayers(); // [{ id, name, visible, locked, level, radio }]
if (layers.length) viewer.setLayerVisible(layers[0].name, false); // pages and thumbnails follow
viewer.on('layersChange', (e) => console.log(e.layers.filter((l) => l.visible).map((l) => l.name)));
文本选择与搜索
页面上方覆盖着一层透明的文本层(textLayer: true,默认值),使文本可以被选择和复制。搜索栏可通过 Ctrl+F 或工具栏按钮打开;在代码中:search(query, { caseSensitive, wholeWord }) 会高亮每个匹配项,并显示当前页或其后的第一个匹配项;searchNext() 和 searchPrev() 用于移动(并循环);clearSearch()、getSearch()、showSearch()、hideSearch();事件 searchChange。查询中的空白字符可匹配任何空白字符或换行。getPageText(n) 返回搜索所使用的页面文本。
const state = await viewer.search('invoice', { caseSensitive: false });
console.log(state.total, state.index, state.page); // matches, current match (0-based), its page
viewer.searchNext();
console.log(await viewer.getPageText(1));
页面编辑
设置 pageEditing: true 后,缩略图面板会显示页面工具栏(向左 / 向右旋转、上移 / 下移、删除、插入 PDF 文件、撤销、重做):单击选择缩略图(Ctrl / Cmd + 单击,Shift + 单击选择范围),将其拖到新位置;也可以将桌面上的 PDF 文件拖放到面板上以插入其页面。同样的操作也可以通过代码完成(即使未设置该选项),每一步均可撤销:
const ed = VibeFoxJSPdf.createPdfViewer('#app2', { document: await VibeFoxJSPdf.loadPdf(pdfBytes), pageEditing: true, sidebar: 'thumbnails' });
ed.selectPages([0, 1]);
ed.rotatePages(); // the selected pages, 90° clockwise
ed.movePages([2], 0); // page 3 to the front
await ed.insertPages(file, { at: 1, pages: '1' }); // the first page of another PDF file after page 1
ed.removePages([3]);
ed.undo();
ed.on('pageEdit', (e) => console.log(e.action, e.pages));
方法:selectPages、getSelectedPages、rotatePages(indices, angle)、removePages(indices)、movePages(indices, to)、insertPages(source, { at, pages, password })、undo、redo、canUndo、canRedo;事件 pageEdit、pageSelectionChange、pageInsertError。最后一页永远不会被删除。这些更改属于文档本身的更改,照常保存即可。
打印
工具栏中的打印按钮(位于搜索和下载之间)以及 print(options) 会通过浏览器的打印对话框打印文档。页面以打印分辨率的图像形式绘制到页面中的隐藏框架中:不会打开新窗口,查看器不会改变,打印完成后框架会被移除。仅包含用于打印的注释——print: false 的注释会被排除,而 annotations: false 会排除全部注释;表单值和可见图层按显示的样子打印。
const result = await viewer.print({
pages: '1-2', // 'all' (default), 'current', '1-3, 5, 8-' or [1, 3]
dpi: 200, // default 150, 72 … 600
onProgress: (e) => console.log(`page ${e.page}: ${e.done} of ${e.total}`),
});
console.log(result); // { pages: [0, 1], total: 2, dpi: 200 } after the dialog
viewer.on('printProgress', (e) => console.log(e.done, e.total));
console.log(viewer.canPrint());
- 选项:
pages、dpi、title(打印作业的标题;默认为文档标题,否则为filename)、annotations、renderer、worker、signal(AbortSignal)、onProgress。Promise 在对话框关闭后解析(无文档时为null)。 - 准备页面期间,按钮显示 "Cancel printing",提示行显示进度;调用
cancelPrint()或再次调用print()即可取消(Promise 会以AbortError被拒绝,code: 'abort')。事件:每页之后触发printProgress { page, done, total },对话框弹出前触发print { pages, total, window }。 - 已打开文件的权限同样生效:若文件禁止打印,且未使用所有者密码打开,则无法打印(
canPrint()返回false,按钮被禁用,print()以code: 'permission'被拒绝);若没有高质量打印权限,分辨率最高为 150 dpi。其他错误:code: 'renderer'(设置了renderer: 'pdfjs'但未连接 pdf.js),以及页码超出范围时的RangeError。 - 设置
forms: true时,动作为'print'的表单按钮会通过print()打印。
不使用查看器绘制页面
await renderPageToCanvas(doc, pageIndex, canvas, options) 将一个页面(从 0 开始计数)绘制到 canvas 中:scale(每 pt 的 CSS 像素数)、background、annotations、fields、intent: 'print'(仅包含用于打印的注释)、layers、region(大页面的一个分块)、renderer、signal(AbortSignal)。结果为 { width, height, original, renderer }。
const canvas = document.createElement('canvas');
const info = await VibeFoxJSPdf.renderPageToCanvas(doc, 0, canvas, { scale: 0.5, background: '#ffffff' });
console.log(info.width, info.height); // a thumbnail of page 1
document.body.append(canvas);
渲染 PDF 文件
用本库创建的页面根据其自身的绘图指令进行绘制。已打开文件的原始内容由库自带的 PDF 渲染器绘制,因此查看器、缩略图、文本层、搜索、图层面板、可视比较以及设计器的基础 PDF 均无需其他组件。它涵盖 ISO 32000-1 的内容:所有图形和文本运算符,所有字体类型(TrueType、Type 1、CFF、Type 3、CID 字体;嵌入字体会以字体形式提供给浏览器),所有色彩空间、着色、图案、软蒙版、混合模式、透明度组、可选内容(图层)、注释外观和表单控件,以及图像格式 Flate、LZW、RunLength、JPEG、JPEG 2000、CCITT 和 JBIG2。
- 速度(在 headless Chrome 中、缩放比例 1.5 下,对一本 1,202 页的手册测得):文件打开耗时 15 ms;依次绘制全部 1,202 页耗时 3.8 秒(每页中位数为 2.9 ms);为搜索提取所有页面的文本耗时 0.89 秒。查看器只绘制可见的页面。
- 工作会被分割为多个时间片,因此页面保持响应;离开视口的页面的渲染会被取消。
- Web Worker:默认情况下,渲染器在一个 Worker 中运行,该 Worker 加载同一个库文件(通过
http(s)),若失败则静默回退到主线程。useLiteWorker(false)可将其关闭;当库文件无法自行找到时(例如文件被重命名或内联),useLiteWorker({ url, type })用于提供库文件的 URL。 - 内存:解码后的图像、解析后的内容和字体按每个已打开文件进行缓存,默认为 64 MB;
liteCacheLimit(bytes)用于更改缓存上限(0 表示不缓存),并返回之前的值。
renderer 选项与 pdf.js
查看器、比较视图、设计器、renderPageToCanvas 和 comparePdf 的选项 renderer 用于决定由谁绘制已打开文件的原始内容:'auto'(默认:若已连接 pdf.js 则使用 pdf.js,否则使用自带渲染器)、'lite'(始终使用自带渲染器)或 'pdfjs'(仅使用 pdf.js;未连接时,提示行会说明仅显示通过库添加的绘制内容)。pdf.js 从不属于库本身:可通过 usePdfJs(pdfjsLib, { workerSrc, cMapUrl, standardFontDataUrl, wasmUrl }) 为所有查看器连接自己的副本,也可通过单个查看器的选项 pdfjs 连接(其命名空间或 pdf.mjs 的 URL,首次使用时导入);usePdfJs(null) 用于断开连接。
VibeFoxJSPdf.createPdfViewer('#app2', { document: await VibeFoxJSPdf.loadPdf(pdfBytes), renderer: 'lite' });
VibeFoxJSPdf.useLiteWorker(true); // default
const previous = VibeFoxJSPdf.liteCacheLimit(32 * 1024 * 1024);
底层函数
await renderPageLite(page, canvas, options) 使用自带渲染器,将已打开文件中一个页面的原始内容绘制到 canvas 或 OffscreenCanvas 中(选项:scale、pixelRatio、background、annotations、forms、intent、layers、region、timeSlice、signal;text: true 还会返回带有位置信息的文本项),并在 unsupported 中报告无法绘制的内容。layersLite(doc) 列出已打开文件的可选内容组。
const opened = await VibeFoxJSPdf.loadPdf(pdfBytes);
const c = document.createElement('canvas');
const r = await VibeFoxJSPdf.renderPageLite(opened.page(0), c, { scale: 1, text: true });
console.log(r.width, r.height, r.unsupported, r.text.length, VibeFoxJSPdf.layersLite(opened));
文本提取与搜索
任何文档(包括用库创建的页面和已打开的文件)的文本都由库自身读取,无论是在浏览器中还是在 Node 中。await doc.extractText({ pages }) 返回 { text, pages: [{ page, text }] };await doc.searchText(query, { pages, caseSensitive, wholeWord }) 返回匹配项及其在页面上的区域([{ page, text, rects }],单位为页面 pt)。查询可以是文本、正则表达式,或预设模式之一:'email'、'phone' 和 'card'(REDACTION_PATTERNS)。
const { text, pages } = await doc.extractText();
console.log(pages.length, text.slice(0, 80));
const hits = await doc.searchText(/\d+\.\d\d EUR/);
console.log(hits.map((h) => `${h.page + 1}: ${h.text}`));
const emails = await doc.searchText('email');
文本顺序即内容的绘制顺序;注释中的文本不包括在内。
注释
注释是叠加在页面上的批注,并以真正的 PDF 注释形式(连同其外观)保存,因此所有 PDF 阅读器都能显示;由本库保存的文件可无损地读回。类型(ANNOTATION_TYPES):'highlight'、'underline'、'strikeout'、'squiggly'、'ink'、'rect'、'ellipse'、'line'(带线端箭头的线条)、'polyline'、'polygon'、'note'(可带回复)、'freetext'、'stamp' 和 'signature'。
通过代码添加
doc.addAnnotation(0, { type: 'highlight', rects: [[50, 56, 150, 22]], text: 'Check this number', author: 'Anna' });
doc.addAnnotation(0, { type: 'note', x: 500, y: 100, text: 'Please confirm the total.' });
doc.addAnnotation(0, { type: 'rect', rect: [45, 50, 220, 40], color: '#dc2626', width: 2 });
doc.addAnnotation(0, { type: 'line', points: [[300, 200], [400, 150]], arrow: true, color: '#2563eb' });
doc.addAnnotation(0, { type: 'freetext', rect: [300, 220, 200, 40], text: 'Updated in March', fontSize: 11 });
const stamp = doc.addAnnotation(0, { type: 'stamp', stamp: 'approved', x: 380, y: 60 });
doc.updateAnnotation(stamp.id, { rect: [380, 60, 160, 40] }); // move / resize
console.log(doc.getAnnotations({ page: 0 }).map((a) => a.type));
注释是纯 JSON 数据:{ id, type, rect: [x, y, w, h], color, fill, opacity, width, dash, text, author, subject, created, modified, … },外加其类型的字段(文本标记的 quads 或 rects、墨迹的 paths、points 和 lineEnds、便签的 icon 和 replies、文本框的 font / fontSize / align、图章的 stamp / label / image)。预设图章(PDF_STAMPS,标签位于语言文件中):approved、notApproved、rejected、draft、final、confidential、topSecret、forComment、reviewed、received、paid、void、expired、copy;或自定义的 label 或 image。
文档方法:addAnnotation(page, data)、getAnnotations({ page, type })、getAnnotation(id)、updateAnnotation(id, patch)、removeAnnotation(id);页面上也有相同的方法(page.addAnnotation(data),…)。文档事件:annotationAdd、annotationChange、annotationRemove。已打开文件中的注释同样会被读取:常见类型可以编辑;其他类型(其他程序的图章、附件等)为 readOnly,它们保持原有外观,可以添加评论或删除。
数据交换与拼合
const json = doc.exportAnnotations(); // { v: 1, annotations: [...] }, images as data URLs
const xfdf = doc.exportAnnotations({ format: 'xfdf' }); // the XML exchange format of PDF readers
const copy = VibeFoxJSPdf.PdfDocument.fromJSON(doc.toJSON());
copy.importAnnotations(xfdf, { replace: true });
copy.flatten({ annotations: true, forms: true }); // annotations, signatures and fields become page content
在查看器中
注释始终可见。annotations: true 会添加注释工具栏(工具、8 种颜色、线宽、不透明度、撤销、重做、删除)并启用编辑功能:选择、移动、调整大小、编辑便签和文本框。annotationTools 用于限定可用的工具(PDF_ANNOTATION_TOOLS:'select'、'highlight'、'underline'、'strikeout'、'squiggly'、'ink'、'rect'、'ellipse'、'line'、'arrow'、'polyline'、'polygon'、'note'、'freetext'、'stamp'、'signature'),author 会被写入新注释。
- 文本标记:选中文本后选择工具(或先选择工具再选中文本);在没有文本的页面上,或按住 Alt 时,拖动绘制一个框。
- 墨迹:用鼠标、手写笔或手指绘制;2 秒内的笔画会合并为一个注释。
- 形状:拖动绘制(按住 Shift 可绘制正方形和 45° 线);折线和多边形:单击各个点,双击或按 Enter 结束。
- 便签:单击放置,然后弹出包含文本和回复的弹出框;文本框:拖出一个框并输入文字。
- 图章:提供预设图章菜单以及 "own image" 选项;图章会跟随指针移动,直到单击放下。
const av = VibeFoxJSPdf.createPdfViewer('#app2', { document: doc, annotations: true, author: 'Anna', annotationTools: ['select', 'highlight', 'note', 'stamp'] });
av.setTool('highlight');
av.on('annotationAdd', (e) => console.log(e.annotation.type, e.page));
av.placeStamp({ stamp: 'paid' }); // follows the pointer until a click
av.setTool('select');
方法:setTool、getTool、selectAnnotation(id)、getSelectedAnnotation、deleteAnnotation(id)、editAnnotation(id)、placeStamp(options)、undo、redo、canUndo、canRedo(100 步);事件 toolChange、annotationSelect、historyChange、stampPlace、annotationAdd、annotationChange、annotationRemove。
可视签名
可视签名是放置在页面上的手写签名图片(加密签名参见 数字签名)。签名数据为 { kind: 'draw' | 'text' | 'image', paths | text + image | image, width, height, color }:drawnSignature(strokes) 根据笔画(CSS px)生成签名,typedSignature(name) 根据输入的姓名生成签名(使用草书系统字体绘制为带透明度的 PNG;变量 --vfjs-pdf-signature-font 保存字体栈),await imageSignature(file) 根据 PNG / JPEG 生成签名。
const sig = VibeFoxJSPdf.drawnSignature([[[0, 20], [20, 0], [40, 25], [60, 5], [80, 18]]], { color: '#1e3a8a' });
doc.page(0).addSignature(sig, 360, 720, { width: 120, date: true, author: 'Anna Berg' });
const typed = VibeFoxJSPdf.typedSignature('Anna Berg');
viewer.addSignature(typed, { page: 1, x: 60, y: 720, width: 140 });
在查看器中,签名工具(或 openSignatureDialog())会打开一个对话框,其中包含 Draw、Type、Image 和 Saved 标签页、墨迹颜色、"add the date"(signatureDate)以及 "save for next time" 选项:事件 signatureSave 会提供数据;是否保存这些数据由页面自行决定,选项 signatures 会再次提供它们。placeSignature(data) 让用户通过单击放置签名,addSignature(data, { page, x, y }) 将其放在指定位置;事件 signatureCreate、signaturePlace。
表单
可填写的 PDF 表单(AcroForm)。每个字段都带有外观,因此各阅读器的显示效果一致;其值可以被填写、读取、检查和交换,适用于用库创建的字段,也适用于已打开文件中的表单。
创建字段
const form = new VibeFoxJSPdf.PdfDocument();
const fp = form.addPage();
fp.text('Name', { x: 50, y: 60 });
fp.addTextField('name', 150, 55, 200, { required: true, tooltip: 'Your full name' });
fp.addTextField('amount', 150, 85, 100, { format: { type: 'number', decimals: 2, min: 0 }, align: 'right' });
fp.addTextField('email', 150, 115, 200, { format: 'email' });
fp.addCheckbox('terms', 150, 145, { checked: false });
fp.addRadioButton('plan', 'basic', 150, 175);
fp.addRadioButton('plan', 'pro', 220, 175, { checked: true });
fp.addComboBox('country', 150, 205, 150, { options: ['Norway', 'Sweden', { value: 'FI', label: 'Finland' }], value: 'Norway' });
fp.addListBox('region', 150, 235, 150, { options: ['North', 'South', 'East'], multiple: true, height: 50 });
fp.addSignatureField('signature', 150, 300, 180, 50);
fp.addButton('reset', 150, 370, 80, 24, { label: 'Reset', action: 'reset' });
fp.addButton('send', 240, 370, 80, 24, { label: 'Send', action: { submit: 'https://example.com/form', format: 'xfdf' } });
每个字段都可以设置 readOnly、required、noExport、tooltip(同时也是无障碍名称)、borderColor 和 background。文本字段还可以设置 value、height、fontSize(0 = 自动)、multiline、password、align、maxLen、font(已注册的字体族,支持任何文字)以及 format:'number'、'date'、'email'、{ type: 'number', decimals, min, max, decimalSeparator }、{ type: 'date', pattern }、{ type: 'pattern', pattern, message }(数字和日期格式也会由 PDF 阅读器在输入时应用)。按钮只支持安全的动作:'reset'、'print'、{ url }、{ submit, format },不支持 JavaScript。
填写与读取
form.setFieldValues({ name: 'Anna Berg', amount: '42', terms: true, plan: 'basic', country: 'FI', region: ['North', 'East'] });
console.log(form.getFieldValue('plan'), form.getFieldValues());
const check = form.validateForm(); // { valid, errors: [{ name, code, message }] }
const xfdf = form.exportFormData({ format: 'xfdf' }); // also 'json' (default) and 'fdf'
form.resetForm(['amount']);
form.importFormData(xfdf); // JSON, FDF or XFDF, detected
form.signField('signature', VibeFoxJSPdf.typedSignature('Anna Berg'), { date: true });
console.log(form.getFields().map((f) => `${f.name}: ${f.type}`), check.valid);
getFields() / getField(name) 用于描述字段({ name, type, value, source, options, required, readOnly, format, page, widgets, … })。值的类型:文本和组合框为字符串;列表为字符串或数组;复选框为 true / false;单选组为导出值或 null。validateForm() 检查必填字段、格式、范围和最大长度(代码为 'required'、'format'、'range'、'maxLength')。事件 fieldChange。flatten({ forms: true }) 会将字段转换为页面内容。已打开文件中的表单以相同方式填写(名称为完整名称,即 parent.child),并以增量更新方式保存。
在查看器中填写
设置 forms: true 后,查看器会在字段上方放置真正的输入控件:文本输入、复选框、跨页的单选组、列表、签名字段的签名对话框、页面的键盘顺序、ARIA 名称和错误信息。取值会立即写入文档。提交按钮从不直接发送任何内容:它会验证表单,并以取值触发 formSubmit;formAction 先执行,可以阻止默认行为(defaultPrevented = true)。
const fv = VibeFoxJSPdf.createPdfViewer('#app2', { document: form, forms: true });
fv.on('fieldChange', (e) => console.log(e.name, e.value));
fv.on('formSubmit', (e) => { if (e.valid) console.log('send these values yourself:', e.values); });
const result = fv.validateForm(); // marks the invalid fields, focuses the first one
console.log(result.valid);
脱敏
脱敏会永久删除内容:标记区域下的文本、矢量图形和图像像素会从文件中移除,而不是被涂盖,并在其位置绘制一个方框。它适用于用库创建的文档和已打开的文件(包括加密文件),可在浏览器和 Node 中使用。
const pdf = await VibeFoxJSPdf.loadPdf(pdfBytes);
pdf.addRedaction(0, [50, 90, 200, 14]); // an area [x, y, w, h], page pt
const found = await pdf.redactText(['email', 'phone', 'iban'], { text: 'REMOVED' });
console.log(found.map((m) => m.match)); // review the marks before applying
pdf.removeRedaction(found[0].id);
const result = await pdf.applyRedactions({ metadata: true, bookmarks: false });
console.log(result.marks, result.removed.text, result.warnings);
const clean = await pdf.toBytes(); // always written as a new file now
- 先添加标记:
addRedaction(page, area, { color, text, textColor, label })(区域为[x, y, w, h],也可以是多个{ rects },或选区的{ quads }),redactText(query, { pages, caseSensitive, wholeWord, padding })(查询可以是文本、正则表达式,或预设模式'email'、'phone'——包括带+的国际号码、括号内带区号的号码、10 位及以上数字,以及555-1234这类本地号码;以年份开头的文档编号(2026-001)、带数字分组的日期和金额不会被匹配——,'card'——13 至 19 位数字并通过 Luhn 校验,'iban'——每四位一组或不带空格,并通过 mod 97 校验;REDACTION_PATTERNS列出了这些模式)。跨两行断开的匹配项(电话号码、IBAN、卡号)为一个标记,每行各有一个矩形,其match中以空格代替换行。另有getRedactions()、removeRedaction(id)、clearRedactions(page)。标记仅保存在内存中:在应用之前保存时会提示内容仍在文件中。 applyRedactions(options)会删除中心位于区域内的字符(行中其余部分保持原位)、区域内的形状和图像(跨越区域的形状会被裁剪,跨越区域的图像会在像素上涂盖),以及与区域相接触的注释、链接和表单字段,并绘制方框(默认为黑色;text为叠加文本,textColor默认为白色)。选项:color、text、textColor、ids、pages、metadata、xmp、bookmarks、attachments、javascript(同时删除文件中的这些部分)、keepMarks。结果中会统计被删除的内容数量。- 此后文档总是以新文件的形式写入(增量更新会保留旧字节)。已脱敏文件的签名将失效。
在查看器中,设置 redaction: true 会添加脱敏工具栏:"Mark area"(拖动绘制方框)、"Mark selected text"、带有 "Mark all" 的模式 / 文本 / 正则表达式搜索、标记列表(跳转到某个标记、将其删除),以及带确认的 "Apply redactions"。标记始终可见。方法:setRedactionMode('area' | null)、getRedactionMode、redactSelection()、redactSearch(query)、applyRedactions(options)、toggleRedactionList(open);事件 redactionModeChange、redactionAdd、redactionRemove、redactionApply。
文档比较
await comparePdf(from, to, options) 在浏览器和 Node 中逐词比较两个 PDF 文档的文本(输入可以是 PdfDocument、字节数据、Blob 或 URL)。换行、宽度和字号不计入比较,因此仅重新排版而未改动内容的文本不视为更改;行末断开的连字符单词会被合并。
const cmp = await VibeFoxJSPdf.comparePdf(oldBytes, newBytes, { mode: 'document', ignoreCase: false });
console.log(cmp.summary.changes, cmp.summary.similarity);
for (const c of cmp.changes) console.log(c.type, JSON.stringify(c.old.text), '→', JSON.stringify(c.new.text), c.new.pages);
const report = cmp.toHtml({ title: 'Contract changes' }); // a standalone HTML report; cmp.toJSON() as data
- 选项:
mode('document':整个文本,移动到其他页面的文本不视为更改;'page':第 i 页与第 i 页比较)、ignoreCase、ignorePunctuation、joinHyphens(默认true)、password、visual(浏览器中:同时比较匹配页面的像素:true或{ scale, threshold, images })、renderer、pdfjs。 - 结果包括:
summary(changes、inserted、deleted、equal单词数、similarity、页数和单词数)、changes({ id, type: 'insert' | 'delete' | 'replace', old, new, words },两侧各自包含其text、pages和区域rects)、pages(每页的更改,以及每个新页面对应的旧页面)、visual(每对页面的更改比例和区域)。
比较视图
createPdfCompare(target, { from, to }) 并排显示两个文档并同步滚动:删除内容在旧文档中标出,插入内容在新文档中标出,替换内容以轮廓线标出;同时提供更改列表、上一个 / 下一个按钮,以及 JSON / HTML 报告的下载。layout: 'overlay' 仅显示新文档,并在其上标出所有更改。
const cv = VibeFoxJSPdf.createPdfCompare('#app', { from: oldBytes, to: newBytes, layout: 'side', list: true });
cv.on('compareComplete', (e) => console.log(e.result.summary.changes));
cv.on('changeSelect', (e) => console.log(e.index, e.change.type));
await cv.compare();
cv.nextChange();
cv.setLayout('overlay');
选项 from、to、layout、syncScroll、list、zoom、mode、ignoreCase、ignorePunctuation、visual、renderer、pdfjs、password;方法 compare()、setDocuments(from, to)、getResult()、getViewers()、setLayout()、setZoom()、goToChange(i)、nextChange()、prevChange()、getReport('json' | 'html')、downloadReport(format);事件 compareComplete、compareError、changeSelect、layoutChange。
数字签名
使用证书进行的加密签名:signPdf(input, options)(或 doc.sign(options))对文档签名,并返回已签名的 PDF 字节数据;verifyPdf(input, options) 检查文件中的每个签名。签名使用 WebCrypto(crypto.subtle:在浏览器中需要安全页面,Node 为 19 及更高版本);库本身从不发起网络请求,时间戳和吊销数据均通过自定义回调提供。
签名
// p12File: a .p12 / .pfx file chosen by the user; password: typed by the user
const signed = await VibeFoxJSPdf.signPdf(doc, {
pkcs12: { data: await p12File.arrayBuffer(), password },
reason: 'Approved',
location: 'Oslo',
page: 0,
rect: [360, 700, 190, 60], // visible signature box; no rect = invisible
appearance: { signature: VibeFoxJSPdf.typedSignature('Anna Berg') },
});
const report = await VibeFoxJSPdf.verifyPdf(signed, { trusted: rootPem });
console.log(report.status, report.signatures[0].signer.commonName);
- 密钥:
pkcs12(.p12 / .pfx 文件及其密码;loadPkcs12(bytes, password)返回{ key, certificate, chain }),或key(私钥CryptoKey:RSA PKCS#1 v1.5、RSA-PSS、ECDSA P-256 / P-384 / P-521、Ed25519),并配合certificate和chain(DER 或 PEM),或使用签名器对象{ algorithm, sign(data) },用于硬件令牌或签名服务器。 format:'pades'(默认,ETSI.CAdES.detached,即 PAdES B-B)或'pkcs7'(adbe.pkcs7.detached);hash:SHA-256 / 384 / 512。- 位置:
field(已有的空签名域,否则为第一个空域,再否则新建一个字段)、page+rect(可见签名)或不设置 rect(不可见签名)。appearance:左侧为可视签名,右侧为文本行(默认文本 "Digitally signed by …"、日期、原因、位置;text中可使用{name}{date}{reason}{location}),font、fontSize、color、background、border;locale为默认文本的语言区域。 name、reason、location、contactInfo、date;certify: 1 | 2 | 3(认证签名:1 为不允许任何更改,2 为允许填写表单和签名,3 还允许添加注释;仅可作为第一个签名使用);lock(由该签名锁定的字段:true、字段名称或{ action, fields })。timestamp:回调函数,接收{ request, hash, hashAlgorithm, nonce }——其中request为 RFC 3161 请求(使用Content-Type: application/timestamp-query将其 POST 到时间戳服务机构),回调返回响应字节数据;revocation: { ocsps, crls }用于嵌入吊销数据。- 签名是增量更新:之前的签名保持有效。文档对象本身不会改变;如需继续处理已签名的文件,请使用
loadPdf打开结果。timestampPdf(input, { timestamp })用于添加文档时间戳。
验证
verifyPdf(input, { trusted, certificates, revocation, password, time })(或 doc.verifySignatures())检查每个签名的完整性、签名值、直至 trusted 中受信任根证书的证书路径、签名时间时的有效性(已验证的时间戳,否则为声明的时间)、吊销状态(嵌入的数据、文档安全存储区以及自定义的 revocation 回调),以及签名后所做的更改。报告为 { status, valid, signatures, certified, revisions, warnings };每个签名的 status 为 'valid'、'modified'(签名后发生了超出允许范围的更改)、'invalid' 或 'unknown'(签名者未能追溯到受信任的根),并包括签名者、时间及其来源、时间戳、认证级别、锁定的字段以及之后更改的列表。
在查看器中,已签名的文件会显示状态行,并在侧边栏中出现 "Signatures" 标签页,其中列出每个签名的详细信息。通过选项 signatureValidation: { trusted, certificates, revocation } 提供受信任的根证书;verifySignatures() 会再次检查,getSignatureReport() 返回最近一次的报告,事件 signaturesVerify。
长期验证
addValidationData(input, { revocation, trusted, certificates, timestamp })(或已打开的已签名文件的 doc.addValidationData())会将证书以及每个签名的 OCSP / CRL 数据写入文档安全存储区(PAdES B-LT);若设置了 timestamp,随后会添加文档时间戳(B-LTA)。自定义的 revocation(q) 回调会为每个证书返回 OCSP 响应或 CRL 字节数据。
加密与权限
setEncryption(options)(或文档选项 encrypt,或仅对一次输出使用 toBytes({ encrypt }))使用 PDF 的标准密码安全机制加密保存的文件:method 为 'aes-256'(默认)或 'aes-128',userPassword(打开文件所需的密码;'' 表示无需提示即可打开,但仍适用权限设置),ownerPassword(完全访问权限;默认为随机生成),permissions(PDF_PERMISSIONS:print、modify、copy、annotate、fillForms、accessibility、assemble、printHighQuality;false 表示不允许),以及 encryptMetadata。
doc.setEncryption({
userPassword: '', // opens without a password
ownerPassword: 'owner-secret',
permissions: { copy: false, modify: false, print: true },
});
console.log(doc.getEncryption().permissions);
const protectedBytes = await doc.toBytes();
const plain = await doc.toBytes({ encrypt: false }); // this output without encryption
已打开的加密文件在保存时会保留其加密设置。若要更改或移除限制了某些操作的文件的加密,需要使用其所有者密码(loadPdf(file, { password: owner }));否则 toBytes() 会以 code: 'permission' 被拒绝。setEncryption(false) 用于移除加密,null 则恢复为默认设置。
PDF/A、PDF/UA 与标记 PDF
适用于所生成文件的归档和无障碍标准,并可对任意 PDF 进行检查和转换。
pdfa:'2b'、'2u'、'2a'、'3b'、'3u'、'3a'(PDF/A-2 / -3),true等同于 2b,或{ part, conformance, strict }。输出会附带 XMP 元数据、sRGB 输出意图以及该标准所需的修正,之后进行检查。默认情况下(strict),若文件不符合标准,toBytes()会以code: 'pdfa'和report被拒绝;strict: false则会写入文件并触发warning事件。pdfua: true:PDF/UA-1(带标记、指定语言、显示标题、嵌入字体);检查发现的问题以warning事件的形式报告,从不作为错误。tagged: true:带有结构树但不声明符合性;lang:文档语言。- 字体:PDF/A 和 PDF/UA 需要嵌入字体。在这些模式下,标准字体族将使用已注册的字体绘制(
standardFonts: { helvetica, times, courier, default },否则使用文档字体,再否则使用第一个已注册的字体族);若没有任何已注册字体,保存将失败并给出说明。
const archive = new VibeFoxJSPdf.PdfDocument({
pdfa: '2u', pdfua: true, lang: 'en-US',
metadata: { title: 'Annual report 2026' },
font: { family: 'Noto Sans' },
});
await archive.loadFont('Noto Sans', 'fonts/NotoSans-Regular.ttf');
archive.text('Annual report', { size: 20, tag: 'H1' });
archive.text('Revenue grew by 12 %.'); // a P element
archive.image(logoPng, { width: 60, alt: 'Company logo' }); // a Figure with alternative text
archive.tag('L', () => {
archive.tag('LI', () => archive.text('First point'));
});
const bytes = await archive.toBytes();
console.log((await archive.checkPdfA()).conforms, (await archive.checkPdfUA()).conforms);
结构
带标记的文档会自动为其内容添加标记:每次 text() 调用生成一个段落(或使用指定的 tag:'H1' … 'H6'、'Caption'、'Code' 等,并带有 lang),图像和 SVG 为图形(alt;alt: '' 或 artifact: true 表示装饰性内容),表格为 Table / TR / TH / TD,链接、表单字段和注释获得各自的元素,页眉、页脚、水印和表格边框为工件(artifact)。HTML 转 PDF 会映射标题、段落、列表、表格、图形、链接以及 lang 属性。若需自定义结构:beginTag(role, { alt, lang, actualText, title, scope, colSpan, rowSpan, key }) / endTag()、tag(role, options, fn)、beginArtifact() / endArtifact()、setRoleMap({ Custom: 'P' })、setLanguage();getStructure() 返回结构树,STRUCT_ROLES 列出标准角色。以方框形式添加的其他 VibeFox JS 库组件为图形;通过 addPageFrom 添加的表格或编辑器文档会保留其表格 / 标题结构。
检查与转换
const pdfaReport = await VibeFoxJSPdf.checkPdfA(pdfBytes, { part: 2, conformance: 'b' });
console.log(pdfaReport.conforms, pdfaReport.errors.map((e) => `${e.rule} ${e.message}`));
const uaReport = await VibeFoxJSPdf.checkPdfUA(pdfBytes);
const { bytes: archived, report } = await VibeFoxJSPdf.convertToPdfA(pdfBytes, { pdfa: '2b' });
console.log(report.conforms, report.fixed.length, report.failed);
checkPdfA 检查 PDF/A-2 / -3 的主要规则(文件结构、输出意图和颜色、字体嵌入、透明度、注释、动作、元数据、附件、可选内容;级别 a:标记);checkPdfUA 检查 PDF/UA-1 中可通过机器验证的规则(结构树、所有内容均已标记或为工件、语言、替代文本、标题级别、表格、列表、结构树中的注释和字段)。错误会标明该标准的对应条款。convertToPdfA(或 doc.toPdfA())可转换任意 PDF,并列出已修复的内容以及无法修复的内容(例如未嵌入的字体、在 sRGB 输出意图下的 CMYK 颜色)。这些检查为内置功能,仅限于所列规则;它们不能替代完整的验证器,也不能替代人工审核。
模板与设计器
模板是以 JSON 描述的页面,包含元素和数据占位符;renderTemplate(template, data, options) 可在浏览器或 Node 中将其转换为 PdfDocument。设计器(createPdfDesigner)可在实时预览上以可视化方式编辑模板。
模板
const template = {
name: 'Invoice',
page: { format: 'A4', margins: { top: 40, right: 40, bottom: 40, left: 40 } },
pages: [{ elements: [
{ type: 'heading', x: 40, y: 40, width: 380, height: 30, text: 'Invoice {{number}}', fontSize: 22 },
{ type: 'text', x: 40, y: 80, width: 300, height: 40, text: '{{customer.name}}\n{{customer.city}}' },
{ type: 'barcode', format: 'qr', x: 465, y: 40, width: 90, height: 90, value: 'INV-{{number}}' },
{ type: 'table', x: 40, y: 150, width: 515, height: 420, data: 'items', columns: [
{ header: 'Item', value: '{{name}}', width: 3 },
{ header: 'Qty', value: '{{qty}}', align: 'right' },
{ header: 'Price', value: '{{price | number:2}}', align: 'right', footer: '{{items | sum:qty*price | number:2}}' },
] },
{ type: 'text', x: 40, y: 590, width: 300, height: 20, text: '{{paid ? "PAID" : "DUE"}}', if: 'total > 0', bold: true },
{ type: 'textfield', name: 'comment', x: 40, y: 620, width: 300, height: 24, tooltip: 'Comment' },
] }],
};
const data = { number: 'A-17', paid: false, total: 1250, customer: { name: 'Anna Berg', city: 'Oslo' },
items: [{ name: 'Widget', qty: 2, price: 450 }, { name: 'Gadget', qty: 1, price: 350 }] };
const invoice = await VibeFoxJSPdf.renderTemplate(template, data, { locale: 'en-US' });
const flat = await VibeFoxJSPdf.renderTemplate(template, [data, data], { mode: 'flat' }); // two invoices, fields drawn
console.log(invoice.pageCount, flat.pageCount, VibeFoxJSPdf.templatePaths(template));
- 元素(
TEMPLATE_ELEMENTS):text、heading、image、line、rect、ellipse、table、barcode、repeat(对每一项重复的块:标签、卡片),以及表单字段textfield、checkbox、radio、combo、list、signature、button。坐标以页面左上角为原点,单位为 pt。 - 从右到左:模板的
dir('ltr'或'rtl')是其元素的默认值,text、heading或table元素的dir会覆盖该值(设计器属性 "Text direction")。在从右到左的元素中,align: 'left'/'right'表示起始端 / 末端(镜像),表格的第一列位于右侧。 - 占位符
{{path}}可带表达式({{qty * price}}、{{paid ? "PAID" : "DUE"}}、比较运算、&&、||)和过滤器(TEMPLATE_FILTERS):number:2、currency:EUR、percent、date:dd.MM.yyyy、upper、lower、capitalize、trim、default:x、sum、avg、min、max、count、join、pad、yesno、first、last,以及自定义过滤器(filters选项)。在表格和重复块中可使用:行中的字段、$index、$number;另外还有$page/$pages、$date、$root。表达式由库自行解析(不使用eval)。 - 元素仅在
if为真时显示;行数超过其区域的表格或重复块会从continueY处续接到新页面,表头行会重复出现,表尾行位于末尾;pages: 'first' | 'last' | 'all'用于选择页面上其他元素出现的位置。带有repeat的页面会按数组的每一项各生成一次。基础 PDF(base)会绘制在页面下方。 - 条形码:
format为'qr'(ecLevel)、'datamatrix'、'code128'、'ean13'、'ean8'、'upca'、'code39'、'itf'、'itf14',以矢量形式绘制;QR 和 Data Matrix 会填满整个方框,不含空白静区(请在其周围留出空白),一维码会在条形下方打印其文本(showText)。 renderTemplate的选项:mode('form'可填写字段,默认;'flat'按字段值绘制)、document(追加到该文档)、fonts、fallbackFonts、documentOptions(元数据、pdfa、tagged等)、locale、currency、filters、resolveImage、base、password、onWarning。若传入记录数组,则所有记录生成一个文档。计算失败的表达式不输出任何内容,并给出警告。- 辅助函数:
normalizeTemplate(template)(补全所有默认值)、fillTemplateText(text, { data })、templatePaths(template)(模板使用的数据路径)。
设计器
createPdfDesigner(target, { template, data }) 是模板的所见即所得编辑器:提供元素选板(将元素拖到页面上),页面按 PDF 的实际效果绘制,可显示占位符或预览数据(preview);支持选择、移动和调整大小,并可吸附到网格和参考线;支持对齐与分布、分组、图层、复制和粘贴、撤销 / 重做、多页、基础 PDF,以及侧边面板(Properties、Layers、Data)。工具栏可保存模板 JSON,并导出可填写的 PDF 或平面 PDF。
const designer = VibeFoxJSPdf.createPdfDesigner('#app', { template, data, preview: true, zoom: 'fit' });
designer.on('templateChange', (e) => localStorage.setItem('invoice-template', JSON.stringify(e.template)));
const el = designer.addElement('text', { x: 40, y: 700, width: 300, height: 20, text: 'Thank you, {{customer.name}}!' });
designer.select(el.id);
designer.align('center', { to: 'page' });
const pdf = await designer.renderPdf({ data, mode: 'flat' });
console.log(pdf.pageCount, designer.getTemplate().pages[0].elements.length);
选项:template、data、preview、zoom(数字,1 = 每个 CSS px 对应 1 pt,或 'fit')、palette(元素类型)、grid、snap、fonts、fallbackFonts、dataLocale、readOnly、panel、renderer、pdfjs。方法:getTemplate、setTemplate、renderPdf、downloadPdf、downloadTemplate、loadBasePdf、removeBasePdf、addElement、getElement、getElements、updateElement、removeElement、select、getSelection、selectAll、clearSelection、align、distribute、arrange、group、ungroup、copy、cut、paste、duplicate、undo、redo、canUndo、canRedo、getPage、goToPage、addPage、removePage、setPageFormat、getZoom、setZoom、zoomIn、zoomOut、getPreview、setPreview、showPanel、focusProperty、getWarnings、getState、setState。事件:templateChange、selectionChange、elementAdd、elementRemove、pageChange、zoomChange、previewChange、panelChange、historyChange、render、renderError。框架封装包会对 template 进行双向绑定。
主题与样式
主题
每个 VibeFox JS 组件的 CSS 文件中都内置了 light(默认)、dark 和 high-contrast 主题。可选的 vibefox-js-themes.css 添加了主题包:high-contrast-light、paper、paper-dark、glass、glass-dark、classic、classic-dark、ocean、ocean-dark、forest、forest-dark、sunset、sunset-dark、graphite、graphite-dark。同一文件适用于所有 VibeFox JS 库。
VibeFoxJSPdf.setTheme('dark'); // the whole page
VibeFoxJSPdf.setTheme('ocean', '#sidebar'); // every component inside a container
viewer.setTheme('glass'); // one component (also: the theme option)
viewer.setTheme(null); // follow the page / container again
未设置自身 theme 的组件会跟随最近的带有主题的容器,然后是页面的主题。调用 setTheme(name, container) 之后,主题变量也会设置在容器本身上,因此容器的自定义 CSS 可以使用它们(#sidebar { background: var(--vfjs-bg); })。自定义主题:使用主题变量调用 registerTheme(name, vars)(bg、fg、border、accent、accent-fg、muted、surface、radius、font、shadow、palette-0 … palette-9 以及其他任何令牌(token)),之后它会立即应用于所有使用该主题的组件。getTheme() 返回页面主题,themes 列出所有已注册的主题;切换主题时会触发 themeChange 事件。
VibeFoxJSPdf.registerTheme('brand', { accent: '#e11d48', 'accent-fg': '#ffffff', radius: '10px' });
viewer.setTheme('brand');
CSS 变量
VibeFox JS PDF 的每种颜色、尺寸、间距、字体、圆角、阴影和动画时长都是 CSS 变量,因此任何设置都可在一处修改。共分三个层级:
- 所有 VibeFox JS 组件共用的主题变量:
--vfjs-bg、--vfjs-fg、--vfjs-border、--vfjs-accent、--vfjs-accent-fg、--vfjs-muted、--vfjs-surface、--vfjs-radius、--vfjs-font、--vfjs-shadow、--vfjs-palette-0…--vfjs-palette-9; - 设计令牌:间距
--vfjs-space-1…--vfjs-space-8,字号--vfjs-font-size、--vfjs-font-size-sm等,圆角--vfjs-radius-sm…,状态颜色--vfjs-danger、--vfjs-success、--vfjs-warning、--vfjs-info,尺寸单位--vfjs-size-unit,动画时长--vfjs-motion-duration,焦点环--vfjs-focus-ring-color和--vfjs-focus-ring-width; - 库自身的变量
--vfjs-pdf-*,其默认值取自上述令牌。
/* all VibeFox JS components of the page */
.vfjs { --vfjs-accent: #0f766e; --vfjs-radius: 4px; }
/* only this viewer */
#preview {
--vfjs-pdf-bg: #e2e8f0; /* workspace around the pages */
--vfjs-pdf-page-gap: 16px;
--vfjs-pdf-page-shadow: none;
--vfjs-pdf-toolbar-bg: #0f172a;
--vfjs-pdf-search-hit: rgb(250 204 21 / .4);
}
变量的主要分组(均以 --vfjs-pdf- 开头):外框与工作区(--vfjs-pdf-bg、--vfjs-pdf-fg、--vfjs-pdf-font、--vfjs-pdf-font-size、--vfjs-pdf-radius、--vfjs-pdf-density),工具栏和按钮(--vfjs-pdf-toolbar-bg、--vfjs-pdf-btn-hover-bg …),页面(--vfjs-pdf-page-bg——纸张颜色、--vfjs-pdf-page-shadow、--vfjs-pdf-page-gap、--vfjs-pdf-body-padding),侧边栏和缩略图(--vfjs-pdf-sidebar-width、--vfjs-pdf-thumb-width …;标签页:--vfjs-pdf-tab-icon-size、--vfjs-pdf-tab-gap、--vfjs-pdf-tab-label-display——默认为 none,inline 会在图标旁显示名称),文本选择与搜索(--vfjs-pdf-selection、--vfjs-pdf-search-hit、--vfjs-pdf-search-current),链接和字段上的方框(--vfjs-pdf-link-highlight、--vfjs-pdf-field-highlight,默认透明),注释(--vfjs-pdf-annot-highlight、--vfjs-pdf-annot-color-0 … --vfjs-pdf-annot-color-7、--vfjs-pdf-stamp-positive …),签名对话框(--vfjs-pdf-sign-color-0 …、--vfjs-pdf-signature-font——用于键入式签名的系统手写字体,不含字体文件),表单字段(--vfjs-pdf-field-bg、--vfjs-pdf-field-focus-bg、--vfjs-pdf-field-invalid),脱敏(--vfjs-pdf-redact-mark-bg …),签名状态(--vfjs-pdf-sig-valid …),比较(--vfjs-pdf-diff-ins、--vfjs-pdf-diff-del、--vfjs-pdf-compare-list-width),设计器(--vfjs-pdf-designer-bg、--vfjs-pdf-designer-grid-color、--vfjs-pdf-designer-selected、--vfjs-pdf-designer-color-0 …)。当页面使用的变量发生变化时,页面会重新绘制。写入 PDF 文件的颜色(注释、模板颜色)以普通颜色形式保存,与主题无关。
在 JavaScript 中:可在组件的元素上设置变量(viewer.el.style.setProperty('--vfjs-pdf-page-gap', '24px'));className 可添加自定义类。
设置位置:可在 :root 上、页面中的任意容器上(#checkout { --vfjs-accent: #0f766e; })、组件的元素上,或在主题中(registerTheme)设置。以最近的值为准;带有自身主题的组件(选项 theme 或 component.setTheme(name))即使位于设置了变量的容器中,也会保留该主题的主题变量。位于另一个组件内部的容器(对话框或卡片中的表单)同样会将库的变量传给其中的组件。仅共享的设计令牌(--vfjs-space、--vfjs-danger、--vfjs-selected-bg …)不会这样传递:请将它们设置在外层组件之外的容器上,或设置在嵌套的组件自身上(#form .vfjs { … })。放置在 <body> 中的弹出框、菜单和对话框采用页面上设置的值(:root),而非其组件所在容器的值。
默认值:主题变量通过 @property 注册(其初始值为浅色主题),因此页面上的每个元素都有值。库的变量(--vfjs-pdf-*)在样式表中、在使用它们的位置保留默认值,因此,未设置的变量在自己的元素上没有值:
- 在自定义的 CSS 中使用库的变量时,请像库一样为其提供回退值:
var(--vfjs-pdf-bg, var(--vfjs-bg)),或直接使用主题变量; - 在 JavaScript 中,使用
cssVar(element, '--vfjs-pdf-page-gap')读取当前值(由库导出;也会返回组件计算出的默认值);对于没有人设置过的库变量,getComputedStyle(element).getPropertyValue()可能返回空字符串。
/* your own element in the colors of the component */
.my-summary { background: var(--vfjs-pdf-bg, var(--vfjs-bg)); color: var(--vfjs-fg); }
const el = document.querySelector('#orders');
console.log(VibeFoxJSPdf.cssVar(el, '--vfjs-pdf-page-gap')); // the value in use (also a default)
console.log(getComputedStyle(el).getPropertyValue('--vfjs-pdf-page-gap')); // can be '' unless you set it
如果库的 CSS 文件来自另一来源且未启用 CORS(<link> 没有 crossorigin 属性),浏览器不允许脚本读取该样式表,因此对于组件根元素上没有值的变量,cssVar() 返回空字符串。从自己的来源加载,或加上该属性,即可正常工作。
--vfjs-pdf-zoom(页面的当前缩放)和 --vfjs-pdf-designer-swatch(单个色块的颜色)本身没有值:库会在这些元素上设置它们,因此无需更改。--vfjs-pdf-density 用于设置查看器间距的密度:--vfjs-pdf-space(间距步长)等于 --vfjs-space-unit × --vfjs-pdf-density,查看器的内边距和间隙都是它的倍数。
样式表使用原生 CSS 嵌套编写;引入它们无需任何更改,自定义 CSS 可采用任意写法。
现成样式
查看器选项 style(框架封装包中的 prop variant)用于选择现成的外观;每种样式都适用于所有主题和密度。
| 样式 | 外观 |
|---|---|
'classic' | 灰色工作区,带有凸起的方形页面。 |
'dark' | 无论采用何种主题,工作区和工具栏均为深色。 |
'minimal' | 无边框,工具栏透明,页面为带轮廓线的平面页面。 |
'compact' | 控件、文本和内边距更小。 |
'paper' | 暖色工作区,纸张带有色调。 |
viewer.setStyle('dark'); // or the option style: 'dark'
viewer.getStyle(); // 'dark'
viewer.setStyle(null); // the default look
PDF_VIEWER_STYLES 列出样式名称;setStyle 会触发 styleChange。样式以类 vfjs-pdf-style-<name> 的形式应用于查看器或任意容器;其他名称则使用为该类编写的自定义 CSS。
密度与尺寸
在页面或任意容器上设置 data-vfjs-density="compact"、"normal" 或 "comfortable":其中所有 VibeFox JS 组件的高度和内边距都会随之变化。--vfjs-size-unit(默认 1px)可同时缩放组件的所有尺寸,例如 #orders { --vfjs-size-unit: 1.25px; }。选项中以数字给出的尺寸为像素值,不会被缩放。
默认高度:当组件的元素本身没有高度时,它会获得类 vfjs-auto-height,并使用变量 --vfjs-pdf-min-height(400 px × --vfjs-size-unit)作为默认高度;对比视图使用 --vfjs-pdf-compare-min-height,同样为 400 px。页面在内部滚动,并且只绘制可见的页面。若元素自身有高度(设置了 height、仅设置了 min-height、作为 flex 项或 CSS Grid 项、父元素有高度时的 height: 100%、绝对定位的 insets),则会获得类 vfjs-fit,并精确填满该元素,即使元素较小也是如此;内容永远不会使其变高。变量设为 0(类 vfjs-content-height)时,查看器与其全部页面等高,且自身不产生滚动。设计器则不同:没有高度时,其高度至少为 --vfjs-pdf-designer-min-height(520 px),并随内容增长;显式设置的高度则精确保留。
自定义 CSS
库的所有规则都位于级联层 @layer vfjs 内,因此自定义 CSS 无需 !important 即可始终生效。VibeFox JS PDF 的类名均以 vfjs-pdf- 开头(状态类同样如此,例如 vfjs-pdf-is-selected),因此页面上的其他 CSS 框架不会改变其样式。
.vfjs-pdf-toolbar { border-block-end: 2px solid #0f766e; }
.vfjs-pdf-thumb.vfjs-pdf-is-current { outline-color: #0f766e; }
库不附带任何字体文件。它使用令牌 --vfjs-font、--vfjs-font-mono 和 --vfjs-font-serif 中的系统字体栈;如需其他字体,可将这些令牌设置为所需字体。动画遵循 prefers-reduced-motion,颜色遵循强制颜色模式(Windows 高对比度)。
本地化与 RTL
语言
VibeFox JS PDF 提供 14 种界面语言。英语(en)内置于库文件中;其他每种语言各有一个语言文件(包中的 dist/locales/vibefox-js-pdf.<lang>.js),页面只加载其所用的语言:俄语(ru)、西班牙语(es)、德语(de)、法语(fr)、意大利语(it)、葡萄牙语(巴西)(pt)、乌克兰语(uk)、土耳其语(tr)、简体中文(zh)、日语(ja)、韩语(ko)、印地语(hi)和阿拉伯语(ar)。locale 选项用于设置单个组件的语言;setLocale(lang) 用于设置页面的默认语言,所有未设置自身 locale 的组件都会跟随它(语言更改时会重新渲染)。
VibeFoxJSPdf.setLocale('ru'); // page default
const viewer = VibeFoxJSPdf.createPdfViewer('#app', { document: doc, locale: 'en' }); // this viewer only
viewer.setOptions({ locale: 'de' });
上面的示例需要其所用语言的文件。使用 script 标签时,应在库之后加载语言文件。顺序很重要:若先加载,该文件不会添加语言,并会向控制台输出警告。
<link rel="stylesheet" href="vibefox-js-pdf.css">
<script src="vibefox-js-pdf.global.min.js"></script>
<script src="locales/vibefox-js-pdf.ru.js"></script>
使用 npm 或打包工具时,请在库之后导入语言。不使用 npm 时,ES 模块页面可导入 ./locales/vibefox-js-pdf.ru.esm.js,它会在 vibefox-js-pdf.esm.js 中注册该语言。
import { createPdfViewer } from '@vibefox/js-pdf';
import '@vibefox/js-pdf/locales/ru';
.esm.js 语言文件不适用于压缩版构建 @vibefox/js-pdf/min(那样会加载第二份库副本)。此时请使用 .json 文件:
import { createPdfViewer, addLocale } from '@vibefox/js-pdf/min';
import ru from '@vibefox/js-pdf/locales/ru.json';
addLocale('ru', ru);
没有对应文件时,locale: 'ru' 会显示英语,并向控制台输出一条警告。
语言代码:uk、ko、zh 和 pt 为标准代码;ua 和 kr 也可用,作为 uk 和 ko 的别名。对于每个字符串,库会依次尝试:精确代码、别名、基础语言(pt-BR → pt、zh-CN → zh)、英语,最后是键本身。normalizeLocale(code) 返回别名对应的标准代码。
语言不会设置文字方向:使用 locale: 'ar' 时,还需在容器上设置 rtl: true 或 dir="rtl"。
添加语言
addLocale(lang, dictionary) 为某种语言添加字符串(若该语言不存在则会创建):可以是自定义语言,也可以是基于某个语言文件的自定义译文。缺失的键会按上述顺序回退,因此可以只提供部分词典;addLocale('ua', …) 会补充 uk。请在使用该词典的组件创建之前添加词典,或之后再切换语言。
VibeFoxJSPdf.addLocale('de', {
pdfZoomIn: 'Vergrößern',
pdfZoomOut: 'Verkleinern',
pdfDownload: 'PDF herunterladen',
});
VibeFox JS PDF 的键为以 pdf 为前缀的驼峰式名称(例如 pdfZoomIn、pdfSearch、pdfAnnot_highlight、pdfTool_ink、pdfRedactApply、pdfCompareNext、pdfDesignerAddPage),涵盖工具栏、搜索栏、侧边栏、注释、签名、表单、脱敏和签名状态文本、比较视图和设计器,以及屏幕阅读器文本。语言文件列出了每个键(locales/vibefox-js-pdf.ru.json);英文文本位于可读文件 vibefox-js-pdf.esm.js 中。花括号中的占位符(例如 {page})由库填充。t(key, params) 用于在页面语言中翻译键,viewer.t(key) 用于在查看器语言中翻译;getLocale() 返回页面语言,onLocaleChange(fn) 报告语言的更改。
复数形式:带数字的文本含有以下键:<key>.zero、.one、.two、.few、.many 和 .other(即 Intl.PluralRules 的类别);.other 为回退形式,因此词典可以只提供该形式。{count} 和 {n} 由库填充。tPlural(key, count, params, lang) 用于选择形式;方法 viewer.tPlural(key, count, params) 则在组件的语言中完成该操作。
VibeFoxJSPdf.addLocale('de', {
'pdfRedactConfirm.one': 'Inhalt unter {count} Markierung entfernen?',
'pdfRedactConfirm.other': 'Inhalt unter {count} Markierungen entfernen?',
});
VibeFoxJSPdf.tPlural('pdfRedactConfirm', 5, {}, 'de'); // 'Inhalt unter 5 Markierungen entfernen?'
组件的语言不会更改 PDF 文件:放入文档的文本由其所有者决定。部分生成的文本遵循其自身的语言区域:预设图章的标签(图章的 lang:页面中该语言的键 pdfStamp_<key>,否则为英语)、可见数字签名的默认文本(signPdf 的 locale)、HTML 页眉和页脚中的 {date}(locale),以及模板的数字、货币和日期过滤器(renderTemplate 的 locale,设计器的 dataLocale)。
从右到左(RTL)
选项 rtl: true 使组件从右到左排版(其元素上设置 dir="rtl");rtl: false 强制从左到右;若不设置,组件将跟随页面或其容器(<html dir="rtl">)。方向键遵循阅读顺序。isRtl(element) 用于返回元素的排版方向。
在 VibeFox JS PDF 中,工具栏、侧边栏、面板和对话框均跟随排版方向;上一页 / 下一页按钮指向阅读方向,书签树的按键遵循阅读顺序;页面和文本层保持 PDF 的几何布局。在 PDF 文档中,从右到左的文本(阿拉伯文、希伯来文)按照 Unicode 双向算法从右向左书写,并由字体进行字形整形(参见 字体 → 从右到左与复杂文字):文本、表格、文档和模板的选项 dir、align: 'start' / 'end',以及 HTML 中的 dir / direction。查看器的文本层、搜索和复制功能会按阅读顺序处理从右到左的文本。
无障碍
查看器是带标签的区域,包含一个工具栏(单个 Tab 停靠点,内部使用方向键),页面为带标签的分组,文本层可被屏幕阅读器读取,并实时播报搜索结果、页面编辑和表单错误。注释是可聚焦的列表项,包含其类型、作者和文本;表单字段为真正的输入控件,带有名称、必填和无效状态;设计器、比较视图、侧边栏以及签名和图章对话框均可完全通过键盘操作。焦点清晰可见(焦点环由 CSS 变量 --vfjs-focus-ring-color、--vfjs-focus-ring-width、--vfjs-focus-ring-offset、--vfjs-focus-ring-style 定义);对话框会将焦点保留在内部,并在关闭时将焦点归还。支持 high-contrast 和 high-contrast-light 主题、强制颜色模式以及 prefers-reduced-motion。有关无障碍 PDF 文件,参见 PDF/A、PDF/UA 与标记 PDF。
键盘
在 macOS 上,凡列出 Ctrl 的地方均可使用 Cmd。
查看器
| 按键 | 操作 |
|---|---|
| Ctrl+F | 打开搜索栏。 |
| Enter, Shift+Enter(搜索栏) | 下一个 / 上一个匹配项。 |
| F3, Shift+F3, Ctrl+G | 下一个 / 上一个匹配项。 |
| Esc | 关闭搜索栏,结束脱敏的区域标记,取消放置。 |
| Ctrl + / Ctrl − / Ctrl+0 | 放大 / 缩小 / 100 %。 |
| Home, End(页面) | 第一页 / 最后一页。 |
| n, j / p, k(页面) | 下一页 / 上一页。 |
| PageDown, PageUp, →, ←(单页布局) | 下一页 / 上一页。 |
| r, Shift+R | 顺时针 / 逆时针旋转视图。 |
| ↑ ↓ Home End Enter Space(缩略图) | 移动,打开页面。 |
| ↑ ↓ ← → Home End Enter(书签) | 移动,展开 / 折叠,打开。 |
注释与页面编辑
| 按键 | 操作 |
|---|---|
| Tab | 移至页面的下一个注释。 |
| 方向键、Shift+方向键、Alt+方向键 | 移动注释(×10),调整其大小。 |
| Delete, Backspace | 删除所选注释 / 所选页面。 |
| Enter | 编辑便签或文本框;为选中的文本添加标记注释。 |
| Ctrl+Enter | 完成(文本框、便签的回复)。 |
| Enter, 双击, Backspace, Esc(折线 / 多边形) | 结束、结束、删除最后一个点、取消。 |
| Enter(放置图章或签名时) | 将其放在当前页面的中央。 |
| Ctrl+Z, Ctrl+Y, Ctrl+Shift+Z | 撤销 / 重做(注释和页面编辑)。 |
| Space, Shift+↑ ↓ Home End, Ctrl+A(缩略图、页面编辑) | 选择页面。 |
| R, Shift+R, Alt+↑ ↓(缩略图、页面编辑) | 旋转、移动页面。 |
设计器与比较视图
| 按键 | 操作 |
|---|---|
| 方向键、Shift+方向键、Alt+方向键(元素) | 按 1 pt / 一个网格步长移动,调整大小。 |
| Space, Delete, Enter / F2, Esc(元素) | 切换选中状态,删除,编辑属性,退出。 |
| Ctrl+A, Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D | 全选、复制、剪切、粘贴、创建副本。 |
| Ctrl+G, Ctrl+Shift+G | 组合 / 取消组合。 |
| Ctrl+], Ctrl+[(Shift:移至最前 / 最后) | 在层叠顺序中前移 / 后移。 |
| Ctrl+Z, Ctrl+Y, Ctrl + / − / 0 | 撤销 / 重做,缩放。 |
| Alt+PageDown, Alt+PageUp(比较视图) | 下一个 / 上一个更改。 |
| ↑ ↓ Home End Enter(更改列表) | 移动,显示更改。 |
屏幕阅读器
角色:查看器为 region("PDF viewer"),工具栏为带有 aria-label 和 aria-pressed 切换按钮的 toolbar;搜索栏为带有实时计数的 search;页面为 group("Page n";画布对屏幕阅读器隐藏);缩略图为 listbox(页面编辑时带有 aria-multiselectable,并使用 aria-current="page");书签为 tree;侧边栏为 tablist;注释为 listbox / option;对话框为带有 aria-modal 的 dialog;提示行和签名状态行为 status。表单字段具有 aria-label(工具提示或名称)、aria-required、aria-readonly 和 aria-invalid。
库还导出了它自身使用的辅助函数:announce(message)、trapFocus、rovingFocus、setAria、prefersReducedMotion() 等(参见 API 参考)。
与其他 VibeFox JS 库配合使用
VibeFox JS PDF 可以独立工作。每个 VibeFox JS 库都是独立文件,并带有共享核心的各自副本;同一页面中的多个库可以无冲突地协同工作:每个库一个全局变量(VibeFoxJSPdf、VibeFoxJSCharts 等)、带库前缀的类名、统一的页面主题,以及一致的事件。
使用 link() 连接组件
link(source, event, target, method, transform) 会在某个组件触发事件时调用另一个组件的方法;它返回一个用于移除该链接的函数。connect(source, event, handler) 用于订阅事件,并返回取消订阅的函数。bus 是页面范围内的事件通道,由页面上的所有 VibeFox JS 库共享。
// two viewers turn their pages together
const second = VibeFoxJSPdf.createPdfViewer('#app2', { document: doc });
const unlink = VibeFoxJSPdf.link(viewer, 'pageChange', second, 'goToPage', (e) => e.page);
VibeFoxJSPdf.bus.emit('docs:saved', { at: Date.now() }); // any library can listen: VibeFoxJSGrid.bus.on('docs:saved', fn)
页面中其他库的作用
- PDF 中的其他 VibeFox JS 库组件:
addComponent()、addComponents()和addPageFrom()可以接收页面上已有的图表、表格、示意图、甘特图、交易图表或编辑器,并将其绘制到文档中(参见 PDF 中的 VibeFox JS 组件)。VibeFox JS PDF 可独立工作;这些调用只需要传入的组件本身。 - 反过来,如果页面中同时存在 VibeFox JS PDF,其他 VibeFox JS 库会识别并将其用于 PDF 功能(例如 VibeFox JS Grid 或 VibeFox JS Diagram 的
toPdfDocument()和previewPDF()):它们会构建本库的PdfDocument,并在 VibeFox JS PDF 查看器中显示。 - VibeFox JS PDF 的其他所有功能(文档、打开文件、查看器、签名、模板)均无需其他库。
API 参考
导出内容
类与工厂函数:PdfDocument、PdfPage、createPdfViewer、VibeFoxJSPdfViewer、createPdfDesigner、VibeFoxJSPdfDesigner、createPdfCompare、VibeFoxJSPdfCompare、PdfComparison。
函数:loadPdf、htmlToPdf、renderTemplate、normalizeTemplate、fillTemplateText、templatePaths、comparePdf、signPdf、timestampPdf、verifyPdf、loadPkcs12、addValidationData、checkPdfA、checkPdfUA、convertToPdfA、srgbProfile、renderPageToCanvas、renderPageLite、layersLite、useLiteWorker、startLiteWorker(内部使用:Worker 端)、liteCacheLimit、usePdfJs、drawnSignature、typedSignature、imageSignature、parsePdf、parseJpeg、resolveFont、measureText、pickEncoding、resolvePageSize、pageFormatName、parseColor、enableComplexScripts(以及标志 complexScripts,参见 从右到左与复杂文字)。
常量:FORMATS、PDF_VIEWER_STYLES、ANNOTATION_TYPES、PDF_ANNOTATION_TOOLS、PDF_STAMPS、PDF_PERMISSIONS、REDACTION_PATTERNS、STRUCT_ROLES、TEMPLATE_ELEMENTS、TEMPLATE_FILTERS、VERSION。
共享核心(所有 VibeFox JS 库中相同):setTheme、getTheme、registerTheme、themes、tokens、componentTokens、densities、cssVar、cssColor、cssLength、observeTokens、setLocale、getLocale、addLocale、normalizeLocale、t、tPlural、withLocale、onLocaleChange、link、connect、bus、Emitter、VibeFoxJSComponent、factory、toCSV、downloadFile、downloadCanvasPNG、createVectorImage、loadVectorImage、announce、trapFocus、rovingFocus、getFocusable、focusFirst、saveFocus、setAria、ensureId、addAriaRef、removeAriaRef、isRtl、mirrorArrow、prefersReducedMotion、prefersHighContrast、motionDuration、onPreferenceChange、injectStyles、ensureBaseStyles、formatNumber、formatDate、escapeHtml、createEl、deepMerge、isPlainObject、getPath、setPath、uid、clamp、debounce、throttle。
PdfDocument 选项
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
format | name 或 [w, h] | 'A4' | 新页面的尺寸(A0–A10、B0–B10、C0–C10、DL、Letter、Legal、Tabloid、Ledger、Executive、Statement;未知名称会抛出 code: 'page-format')。 |
orientation | 'portrait' 或 'landscape' | 'portrait' | 页面方向。 |
margins | { top, right, bottom, left } | { top: 56, right: 50, bottom: 56, left: 50 } | 页边距,单位为 pt。 |
metadata | object | {} | title、author、subject、keywords、creator、producer、creationDate。 |
compress | boolean 或 'auto' | 'auto' | 压缩内容流。 |
font | object | { family: 'helvetica', size: 12, color: '#111111', lineHeight: 1.35, kerning: true, ligatures: true } | 流式排版的默认字体。 |
dir | 'ltr'、'rtl' 或 'auto' | 'auto' | 文本、表格和模板的方向。 |
fonts | array | — | 要注册的字体文件:[{ family, data, weight, style }]。 |
fallbackFonts | string[] | [] | 备用字体族。 |
header, footer | string 或 object | null | 页眉 / 页脚行。 |
watermark | string 或 object | null | 每页的水印。 |
encrypt | object 或 false | — | 保存时的加密设置。 |
pdfa, pdfua, tagged, lang, standardFonts | 参见 PDF/A、PDF/UA 与标记 PDF | — | 所保存文件的符合性。 |
loadPdf 接受相同的选项,另外还有 password 和 onWarning;新页面的 format 默认为文件第一页的尺寸。
PdfDocument 方法
| 方法 | 返回值 | 说明 |
|---|---|---|
addPage, insertPage, page(i), removePage, movePage, rotatePage, copyPages, extractPages, split | 页面 / this / 文档 | 页面(属性:pages、pageCount、currentPage、cursor、outline、metadata、options、sourceInfo)。 |
text, image, svg, table, setCursorY, moveDown, ensureSpace | this / 表格结果 / 页面 | 流式排版。 |
addHtml(html, options) | Promise<{ pages, height, warnings }> | 将 HTML 添加到流式排版中。 |
addComponent, addComponents, addPageFrom | Promise | 以矢量形式添加 VibeFox JS 组件。 |
addImage(src), getImage(id) | id / 图像 | 图像注册表。 |
registerFont, loadFont, setFallbackFonts, getFonts, hasFont | this / Promise / 字体面 / boolean | 字体。 |
setHeader, setFooter, setWatermark, setMetadata, addBookmark | this / 书签 | 装饰与导航。 |
toBytes, save, toDataURL, toBlobURL | Promise | 输出。 |
toJSON(options), PdfDocument.fromJSON(json, options), PdfDocument.merge(...docs) | object / 文档 | 快照与合并。 |
getRenderOps(pageIndex) | ops | 页面的最终绘图指令。 |
addAnnotation, getAnnotations, getAnnotation, updateAnnotation, removeAnnotation, exportAnnotations, importAnnotations, flatten | annotation / 数据 / this | 注释。 |
getFields, getField, getFieldValue, setFieldValue, getFieldValues, setFieldValues, resetForm, validateForm, exportFormData, importFormData, signField | 字段 / 值 / 结果 | 表单。 |
addRedaction, getRedactions, removeRedaction, clearRedactions, redactText, applyRedactions | 标记 / Promise | 脱敏。 |
searchText, extractText | Promise | 文本。 |
sign, addTimestamp, verifySignatures, addValidationData | Promise | 数字签名。 |
setEncryption, getEncryption | this / 信息 | 加密。 |
setConformance, getConformance, beginTag, endTag, tag, beginArtifact, endArtifact, setRoleMap, setLanguage, getLanguage, getStructure, isTagged, toPdfA, checkPdfA, checkPdfUA | this / 值 / Promise | PDF/A、PDF/UA、标记。 |
on, once, off, emit | this | 事件。 |
PdfPage 方法
| 方法 | 返回值 | 说明 |
|---|---|---|
text(text, options), measureText(text, options) | box / number | 定位放置的文本。 |
drawLine, drawRect, drawEllipse, drawCircle, drawPolygon, drawPath | this | 形状。 |
drawImage, drawSvg, drawPage | size / box | 图像、SVG、文档页面。 |
beginGroup, endGroup, group | this | 变换、剪切、不透明度。 |
link(x, y, w, h, target) | this | 链接。 |
addTextField, addCheckbox, addRadioButton, addComboBox, addListBox, addSignatureField, addButton | 字段 | 表单字段。 |
addAnnotation, getAnnotations, updateAnnotation, removeAnnotation, addSignature | annotation | 页面的注释。 |
setRotation(angle) | this | 页面旋转(属性:width、height、margins、contentWidth、contentHeight、index、rotation、isLoaded)。 |
PdfDocument 事件
| 事件 | 负载 | 说明 |
|---|---|---|
change | { type, page, base } | 任何更改(查看器会跟随)。 |
pageAdd, pageRemove | { page, index } | 页面已添加 / 已删除。 |
save | { filename, size } | 通过 save() 保存。 |
warning | { source, messages } | 不支持的 SVG / HTML、保存已签名文件、PDF/A 或 PDF/UA 问题、未应用的脱敏标记。 |
annotationAdd, annotationChange, annotationRemove | { annotation, previous, page } | 注释。 |
flatten | { annotations, forms } | 已拼合。 |
fieldChange | { name, value, previous, reset, signature } | 字段值已更改。 |
redactionAdd, redactionRemove, redactionApply | { redaction } / 结果 | 脱敏。 |
查看器选项
此外,所有 VibeFox JS 组件都接受 theme、locale、rtl 和 on(参见 核心概念)。
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
document | PdfDocument 或 null | null | 所显示的文档。 |
page | number | 1 | 当前页(从 1 开始);在创建时打开,setOptions({ page }) 会翻到该页。 |
zoom, minZoom, maxZoom | number | 1, 0.25, 4 | 缩放。 |
toolbar | boolean | true | 显示工具栏。 |
filename | string | 'document.pdf' | 下载文件的名称。 |
style | string 或 null | null | 现成外观。 |
layout | 'continuous' 或 'single' | 'continuous' | 所有页面连续滚动 / 每次一页。 |
rotation | 0, 90, 180, 270 | 0 | 视图旋转。 |
renderer | 'auto'、'lite'、'pdfjs' | 'auto' | 由谁绘制已打开文件的原始内容。 |
pdfjs | namespace、URL、adapter 或 false | null | 此查看器使用的 pdf.js。 |
sidebar | 'thumbnails'、'outline'、'layers'、'signatures' 或 null | null | 打开的侧边栏视图。 |
textLayer | boolean | true | 页面上可选择的文本。 |
annotations | boolean | false | 注释工具栏和编辑功能。 |
annotationTools | string[] 或 null | null | 注释工具栏的工具。 |
author | string | '' | 新注释的作者。 |
signatures | array | [] | 签名对话框中提供的已保存签名。 |
signatureDate | boolean | false | 对话框中已勾选 "Add the date"。 |
pageEditing | boolean | false | 缩略图面板中的页面工具。 |
forms | boolean | false | 填写表单字段。 |
redaction | boolean | false | 脱敏工具。 |
signatureValidation | object 或 null | null | 已签名文件的受信任根证书、证书以及吊销回调。 |
查看器事件
| 事件 | 负载 | 说明 |
|---|---|---|
ready, optionsChange, themeChange, destroy | 参见 核心概念 | 通用事件。 |
pageChange | { page, pages } | 当前页已更改。 |
zoomChange, rotationChange, styleChange | { zoom }, { rotation }, { style, previous } | 视图已更改。 |
documentChange | { document } | 显示了另一个文档。 |
renderComplete, renderError | { page, original }, { page, error } | 页面绘制完成 / 失败。 |
searchChange, sidebarChange, layersChange | 搜索状态, { view }, { layers } | 搜索、侧边栏、图层。 |
toolChange, annotationSelect, historyChange, stampPlace, annotationAdd, annotationChange, annotationRemove | { tool }, { annotation }, { canUndo, canRedo } … | 注释。 |
signatureCreate, signatureSave, signaturePlace | { signature }, { annotation } | 可视签名。 |
pageEdit, pageSelectionChange, pageInsertError | { action, pages, angle, from }, { pages }, { error, file } | 页面编辑。 |
fieldChange, fieldError, fieldSign, formAction, formSubmit, formValidate | 字段 / 表单负载 | 表单。 |
redactionModeChange, redactionAdd, redactionRemove, redactionApply | { mode }, { redaction }, 结果 | 脱敏。 |
signaturesVerify | { report } | 已检查所显示文件的签名。 |
printProgress, print | { page, done, total }, { pages, total, window } | 打印:某页已准备好 / 接下来打开对话框。 |
查看器方法
| 方法 | 返回值 | 说明 |
|---|---|---|
setOptions, getState, setState, setTheme, on, once, off, t, destroy | — | 通用方法(参见 核心概念)。 |
setDocument(doc, { page }), getDocument, refresh, download | this / 文档 / Promise | 文档。 |
print(options), cancelPrint(), canPrint() | Promise / this / boolean | 打印。 |
goToPage, nextPage, prevPage, setZoom, zoomIn, zoomOut, fitWidth, fitPage, rotate, setRotation, getRotation | this / number | 导航与视图。 |
setStyle, getStyle | this / string | 外观。 |
search, searchNext, searchPrev, clearSearch, getSearch, showSearch, hideSearch, getPageText | Promise / 状态 / this | 搜索。 |
showSidebar, hideSidebar, toggleSidebar, getLayers, setLayerVisible | this / 图层 | 侧边栏与图层。 |
setTool, getTool, selectAnnotation, getSelectedAnnotation, deleteAnnotation, editAnnotation, placeStamp, undo, redo, canUndo, canRedo | this / annotation / boolean | 注释。 |
openSignatureDialog, placeSignature, addSignature | this / annotation | 可视签名。 |
selectPages, getSelectedPages, rotatePages, removePages, movePages, insertPages | this / 页面 / Promise | 页面编辑。 |
validateForm, signField | 结果 / this | 表单。 |
setRedactionMode, getRedactionMode, redactSelection, redactSearch, applyRedactions, toggleRedactionList | this / 标记 / Promise | 脱敏。 |
verifySignatures, getSignatureReport | Promise / 报告 | 数字签名。 |
设计器和比较视图的选项、事件和方法列在各自的章节中(参见 模板与设计器、文档比较)。TypeScript 声明文件(vibefox-js-pdf.d.ts)详细描述了每个选项、负载和返回类型:PdfDocumentOptions、PdfViewerOptions、PdfViewerEvents、PdfAnnotation、PdfSignOptions、PdfSignaturesReport、PdfTemplate、PdfDesignerOptions、PdfCompareViewOptions 等。
故障排除
没有样式
请在脚本旁边引入 vibefox-js-pdf.css。若未引入,组件仍可工作,但没有样式,控制台会显示一条警告 "VibeFox JS stylesheet is not loaded"。使用打包工具时,请导入 @vibefox/js-pdf/css。框架封装包不会自动添加 CSS。
自定义 CSS 不生效,或页面 CSS 框架改变了组件
由于库的 CSS 位于 @layer vfjs 中,自定义规则无需 !important 即可覆盖库规则。若仍不生效,请检查类名:状态类带有库前缀(应为 vfjs-pdf-is-selected,而不是 is-selected)。库从不使用通用类名,因此页面的 CSS 框架不会改变它的样式。
ES 模块无法从磁盘加载
浏览器仅通过 http(s) 加载 <script type="module">。请使用本地 Web 服务器,或使用 vibefox-js-pdf.global.js(它也可以从 file:// 运行)。
内容安全策略(CSP)
库不使用 eval 或内联脚本,也不从网络加载任何内容。它会在其元素上设置内联样式(尺寸和位置),因此使用 style-src 的策略必须允许这些样式(style 属性需要 'unsafe-inline')。已打开 PDF 文件的渲染器通过加载库文件的 Blob URL 启动其 Web Worker(需要 worker-src blob:);若没有该权限,则回退到主线程绘制。打印时,页面图像以 blob: URL 的形式放入隐藏框架中(img-src blob:)。传入的 URL(文件、图像、字体)通过 fetch 加载,因此 connect-src 必须允许这些地址。
字符显示为 "?",或文本未使用自有字体
库不附带任何字体。标准 PDF 字体包含拉丁文和西里尔文字符(以及 'symbol' / 'zapfdingbats' 中的希腊字母、数学符号和装饰符号);其他字符(CJK、阿拉伯文、希伯来文、天城文、₽ …)需要自有的字体文件:请使用 registerFont / loadFont(或选项 fonts)注册 .ttf、.otf 或 .woff 文件并使用其字体族,或通过 setFallbackFonts 添加。不读取 WOFF2 文件:请先将其转换。在 HTML 中,TTF / OTF / WOFF 文件的 @font-face 会自动注册。若阿拉伯文字母未连写,或希伯来文顺序颠倒,说明复杂文字引擎未包含在自己的构建中:请调用 enableComplexScripts()。
保存为 PDF/A 失败
PDF/A 需要嵌入字体:标准字体无法嵌入。请在添加内容之前注册字体文件;它同样会用于标准字体族。错误中包含 report,其中列出未通过的条款;strict: false 仍会写入文件,toPdfA() 则返回文件和报告。
签名或打开 AES-256 文件失败,并提示 crypto.subtle 相关信息
WebCrypto 仅在安全页面(https 或 localhost)以及 Node 19 及更高版本中可用。
没有内容显示,或查看器高度不正确
运行 createPdfViewer 时,目标元素必须已存在(选择器找不到元素时会抛出错误)。查看器会填满其元素:请为该元素设置高度(通过 CSS 或内联样式),或让 flex 或 grid 布局为其提供高度;两者都未设置时,查看器高 400 px(--vfjs-pdf-min-height)。若设置 --vfjs-pdf-min-height: 0,查看器的高度将与其全部页面相同,并且每一页都会被绘制——长文档请避免这样做。
已打开文件的页面只显示新添加的绘制内容
未连接 pdf.js 时设置选项 renderer: 'pdfjs',只会显示用库绘制的内容(提示行会说明这一点)。请使用默认的 'auto' 或 'lite'。
保存已打开的文件时抛出 "permission" 错误
更改或移除受限文件的加密需要其所有者密码:请使用 loadPdf(file, { password: owner }) 打开它。
复制和粘贴不起作用
浏览器仅在安全页面(https 或 localhost)上并且在用户操作之后才允许访问剪贴板。标准字体和嵌入的自有字体的文本可以复制;以图片形式绘制的文本(扫描件)则无内容可复制。
限制
- 字体:不支持竖排文本;字形整形规则仅针对阿拉伯文、希伯来文和天城文——其他印度系文字(孟加拉文、泰米尔文 …)、泰文、高棉文、缅甸文和蒙古文仅获得字体的通用整形,不含其重排规则;两端对齐的文本不会用 kashida 拉伸;不使用字体的 AAT 和 Graphite 表;可变字体使用其默认实例,不支持彩色 emoji、合成粗体 / 斜体,也不支持 WOFF2。
- SVG:不绘制蒙版、滤镜、图案、
textPath、<foreignObject>、GIF / WebP 图像以及重复 / 反射渐变(重复渐变会被填充)。 - HTML 转 PDF:flex 和 grid 布局、浮动、绝对定位、变换、阴影、背景图像、多列、
::before/::after内容、计数器、孤行 / 寡行以及@page :first的排版方式与浏览器不同;外部样式表不会被加载。 - 已打开的文件:JSON 快照仅保留新添加的绘制内容;添加到已打开的标记文件中的内容不会被标记;不支持打开公钥(证书)加密的文件;不写入 RC4 加密。
- 注释:文本框中不支持富文本(只有一种字体、字号和颜色),不支持云形边框、标注、测量注释、附件、声音或影片注释;XFDF 不包含图像;其他程序的图章可以删除,但不能移动。
- 表单:组合框绘制时不带箭头,列表框从第一个选项开始绘制;不支持富文本字段、梳状字段、条形码字段、XFA 表单和计算字段;已打开文件中按钮的动作不会被执行。
- 脱敏:跨越区域的矢量路径会被裁剪,但其几何形状仍保留在文件中;嵌入字体子集会保留被删除字符的字形(保留的是字符集,而不是文本);注释外观中的文本不会被搜索(与区域相接的注释会整体删除);以方框形式绘制的其他文件页面会被裁剪,但不会脱敏;预设模式遵循常见格式,对于不寻常的内容可能遗漏或过度匹配——请在应用之前检查标记。
- 比较:注释中的文本不参与比较;图像和图形仅通过
visual(浏览器)进行比较;多栏页面按其绘制顺序进行比较。 - 数字签名:不发起网络请求(时间戳、OCSP 和 CRL 仅通过自定义回调获取);不检查证书路径的名称约束和策略;吊销数据的时效性会被报告,但不强制执行;每个签名只有一个签名者。
- PDF/A 和 PDF/UA:不提供 PDF/A-1、PDF/A-4 和 PDF/UA-2;不支持 CMYK 输出意图;内置检查仅涵盖所列规则(不包括阅读顺序、对比度或语义检查)。
- 模板:元素不支持旋转,每个文本元素只能有一种字体 / 字号 / 颜色;重复块不能包含表格或其他块,QR 和 Data Matrix 没有静区;设计器预览的是每个模板页面的第一个输出页面。
- 渲染:JPEG 2000 的渐进顺序变化、真实 ICC 配置文件(CMYK 通过拟合公式转换)、注释的
NoRotate/NoZoom、CCITT 未压缩模式以及 JBIG2 颜色扩展无法精确绘制;Worker 需要http(s)以及库文件的 URL。 - 查看器:已打开文件中的链接不可点击;不支持在两个查看器之间拖动页面;拖动页面仅限鼠标 / 手写笔(触摸操作请使用按钮)。
- 框架封装包:选项中的函数按引用比较;移除某个 prop 不会将选项重置为默认值;Vue 对对象类型的 prop 进行浅层监听。
