Skip to content
DemoAPI 参考文档FAQ

PDF 生成模板编辑器

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

查看 GitHub
Guides

注释

使用以下 API 处理注释属性面板、创建和选中事件,以及注释撤销/重做状态。

Reader API

回调或 API参数触发时机
onAnnotationStyleDialogDismissed{ type }注释属性面板关闭。
reader._annotationsHistoryManager.
setOnHistoryStateChangedListener()
canUndo: boolean, canRedo: boolean注释撤销/重做状态变化。

事件监听 API

CPDFReaderView 支持为同一 CPDFEvent 注册多个回调,公共方法如下:

ts
addEventListener<K extends keyof CPDFEventDataMap>(
  event: K,
  callback: (eventData: CPDFEventDataMap[K]) => void
): void;

removeEventListener<K extends keyof CPDFEventDataMap>(
  event: K,
  callback: (eventData: CPDFEventDataMap[K]) => void
): void;

注释事件

事件事件数据触发时机
CPDFEvent.ANNOTATIONS_CREATEDCPDFAnnotation创建非表单注释。
CPDFEvent.ANNOTATIONS_SELECTEDCPDFAnnotation选中注释。
CPDFEvent.ANNOTATIONS_DESELECTEDCPDFAnnotation | null取消选中注释。
CPDFEvent.PENCIL_DRAWING_COMPLETED{ type: 'pencil'; pageIndex: number }Pencil 绘制完成(仅 iOS)。
CPDFEvent.PENCIL_DRAWING_DISCARDED{ type: 'pencil'; pageIndex: number }放弃 Pencil 绘制(仅 iOS)。

注释 Deselected 事件的 TypeScript 类型允许 null,访问对象前应先判空。Pencil 事件仅在 iOS 上触发,返回的 pageIndex 从 0 开始。

这些事件只覆盖创建和选中状态,不提供注释更新、删除或保存失败事件。

注册与移除监听器

使用 useCallback、模块级函数或其他稳定引用保存回调。保存注册监听时的 Reader 实例,避免 Effect 清理时 ref.current 已经变为 null

tsx
const pdfReaderRef = useRef<CPDFReaderView | null>(null);
const subscribedReaderRef = useRef<CPDFReaderView | null>(null);

const onAnnotationCreated = useCallback((annotation: CPDFAnnotation) => {
  console.log("Created annotation:", annotation.type);
}, []);

const onViewCreated = useCallback(() => {
  const reader = pdfReaderRef.current;
  if (!reader || subscribedReaderRef.current === reader) {
    return;
  }

  subscribedReaderRef.current = reader;
  reader.addEventListener(
    CPDFEvent.ANNOTATIONS_CREATED,
    onAnnotationCreated
  );
}, [onAnnotationCreated]);

useEffect(() => {
  return () => {
    const reader = subscribedReaderRef.current;
    if (!reader) {
      return;
    }

    reader.removeEventListener(
      CPDFEvent.ANNOTATIONS_CREATED,
      onAnnotationCreated
    );
    subscribedReaderRef.current = null;
  };
}, [onAnnotationCreated]);

removeEventListener() 返回 void。RN 不提供 removeAllEventListeners(),移除最后一个 JavaScript 监听器时也不会停止原生事件生成。Reader 销毁时会释放本地 Listener Map;当 Effect 重新执行或 Reader 保持挂载时,应显式移除旧监听器。