Skip to content

PDF 生成模板编辑器

开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。

查看 GitHub

Core 桥接 ​

instance.Core 让集成方可以直接访问 Core 对象模型。它是 @compdfkit/core 命名空间,外加三个属于本查看器的成员:

javascript
const {
  documentViewer,      // 主 DocumentViewer
  annotationManager,   // documentViewer.getAnnotationManager()
  getDocumentViewers,  // () => 本 WebViewer 的全部 DocumentViewer 对象
  Annotations, Tools, Actions, SaveOptions, PageRotation, createDocument,
} = instance.Core;

角色与规则 ​

  • instance.Core 是冻结对象。命名空间成员(Annotations、Tools、Document 等)与 UI 使用的是同一套类。
  • 在 UI 内部,组件和 API 不直接调用 @compdfkit/core,而是经由 src/core/ 中的薄封装;这些封装以 documentViewerKey 作为最后一个参数,不保存业务状态。
  • 集成方使用 documentViewer、annotationManager 以及 documentViewer.getDocument() 返回的文档。

文档视图 ​

documentViewer 是主视图(key 为 1)。文档对比功能会创建更多视图;getDocumentViewers() 返回全部视图,instance.UI.getDocumentViewer(key) 按 key 返回其中一个。

javascript
const viewers = instance.Core.getDocumentViewers();
console.log(viewers.length, viewers[0] === instance.Core.documentViewer);

能力一览 ​

文档加载与保存 ​

instance.UI.loadDocument(src, options) 将文档加载到查看器中。documentViewer.getDocument() 返回 Document;Document.getFileData({ flags }) 返回 PDF 数据。instance.Core.createDocument(src, options) 创建一个不显示的 Document。

导航、页面与视口 ​

documentViewer.getPageCount()、getCurrentPage()、setCurrentPage(pageNumber)、getZoomLevel()、zoomTo(zoom)、getViewerElement()、getScrollViewElement(),以及用于坐标转换的 getDisplayModeManager().getDisplayMode()。

搜索与文本 ​

documentViewer.search(text, mode, options) 和 clearSearchResults();getSelectedText() 返回选中的文本。

文档编辑 ​

Document.insertBlankPages、insertPages、removePages、rotatePages、movePages、copyPages、extractPages、setPassword。

注释 ​

annotationManager.addAnnotation(s)、deleteAnnotation(s)、getAnnotationsList()、selectAnnotation、redrawAnnotation、exportAnnotations()、importAnnotations(xfdf)、setCurrentUser(name)、enableReadOnlyMode()、setPermissionCheckCallback(fn)。注释类位于 instance.Core.Annotations。

工具 ​

documentViewer.getTool(toolName)、setToolMode(tool)、getToolMode()。工具类和 ToolNames 位于 instance.Core.Tools。

表单 ​

annotationManager.getFieldManager() 返回 FieldManager(表单域、控件高亮)。

内容编辑 ​

documentViewer.getContentEditManager() 返回 ContentEditManager(startContentEditMode、endContentEditMode、getContentBoxes 等)。

事件 ​

documentViewer.addEventListener(name, handler) 和 annotationManager.addEventListener(name, handler)。参见事件。

示例 ​

读取页数并跳到最后一页 ​

javascript
const { documentViewer } = instance.Core;
documentViewer.setCurrentPage(documentViewer.getPageCount());

导出注释 ​

javascript
const xfdfString = await instance.Core.annotationManager.exportAnnotations();
console.log(xfdfString);

保存文档 ​

javascript
const { documentViewer, SaveOptions } = instance.Core;
const data = await documentViewer.getDocument().getFileData({ flags: SaveOptions.INCREMENTAL });
console.log(data.byteLength);

相关 ​