PDF 生成模板编辑器
开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。
有两种方法可以为 WebViewer 添加自定义设置,第一种方法是通过访问应用程序中的 WebViewer 实例,第二种方法是使用配置文件,配置文件是一个独立的 JavaScript 文件,在 WebViewer 的 iframe 中执行。本文将详细说明第二种。
您可以将自定义代码组织在一个单独的 JavaScript 文件中,该文件在 iframe 的上下文中执行。这样,您就可以直接访问 iframe 的窗口和文档,并直接使用 WebViewer 的全局方法。
如果您将 WebViewer 的 webviewer 文件夹托管在与应用程序不同的服务器上,建议使用配置文件。由于配置文件直接在 iframe 中执行,因此不会出现跨域问题。
要使用配置文件实例化 WebViewer,只需在 WebViewer 构造函数中设置 config 选项即可。例如:
// app.js
ComPDFKitViewer({
path: 'https://myserver.com/',
initialDoc: 'https://www.example.com/test.pdf',
licenseKey: 'Input your license here',
config: 'path/to/your/config.js'
}, document.getElementById('viewer'));config 为相对路径时以界面目录 uiPath(默认 {path}webviewer/,见部署)为基准解析,因此上例实际加载的是 https://myserver.com/webviewer/path/to/your/config.js。界面部署在其他服务器上时,建议直接写完整 URL,文件位置更明确。
界面与您的页面不同源时,外层页面无法拿到 WebViewer 实例:ComPDFKitViewer(...) 返回的 Promise 解析为 undefined,函数类选项(例如回调)也无法传入 iframe。这些代码请写在配置文件中。
配置文件在查看器界面挂载之前、任何文档加载之前执行。在 iframe 内,全局的 instance 对象(instance.UI 与 instance.Core)此时已经可用,您可以监听以下事件,以便在关键节点收到通知。
viewerLoaded 当 WebViewer 完成初始化、界面挂载后,instance.UI 会派发 UI.Events.VIEWER_LOADED 事件。监听该事件,即可执行自定义初始化逻辑,例如修改界面或初始化扩展功能。该事件是粘性的:查看器加载完成后再添加的监听器也会被调用。
// config.js 在内部 iframe 中执行
instance.UI.addEventListener(instance.UI.Events.VIEWER_LOADED, () => {
console.log('viewer loaded');
});documentLoaded documentLoaded 事件触发后,您就可以访问文档以及 DocumentViewer 和 AnnotationManager 上与页面相关的函数。
该事件由 instance.Core.documentViewer 派发。同源时,外层页面也可以通过 ComPDFKitViewer(...) 解析得到的 instance 访问同一个 instance.Core.documentViewer。
// config.js 在内部 iframe 中执行
instance.Core.documentViewer.addEventListener('documentLoaded', () => {
console.log('Document Loaded');
const { annotationManager, Annotations } = instance.Core;
const square = new Annotations.RectangleAnnotation({
PageNumber: 1,
X: 50,
Y: 50,
Width: 50,
Height: 50,
StrokeThickness: 2,
Opacity: 1,
FillColor: null,
StrokeColor: new Annotations.Color(255, 0, 0),
Style: 'solid'
});
annotationManager.addAnnotation(square);
});如果你想从 iframe 内部访问外部页面,例如从配置文件中的代码访问,可以使用 window.parent 访问父窗口。因此,如果你定义了一个加载到 HTML 页面上的 API,就可以像这样从 iframe 内部访问它: window.parent.myApi.myFunction()。