PDF 生成模板编辑器
开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。
使用以下 API 处理注释属性面板、创建和选中事件,以及注释撤销/重做状态。
| 回调或 API | 参数 | 触发时机 |
|---|---|---|
onAnnotationStyleDialogDismissed | { type } | 注释属性面板关闭。 |
reader._annotationsHistoryManager. | canUndo: boolean, canRedo: boolean | 注释撤销/重做状态变化。 |
CPDFReaderView 支持为同一 CPDFEvent 注册多个回调,公共方法如下:
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_CREATED | CPDFAnnotation | 创建非表单注释。 |
CPDFEvent.ANNOTATIONS_SELECTED | CPDFAnnotation | 选中注释。 |
CPDFEvent.ANNOTATIONS_DESELECTED | CPDFAnnotation | 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。
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 保持挂载时,应显式移除旧监听器。