PDF 生成模板编辑器
开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。
ComPDF React Native SDK 自 3.2.0 起支持读取、设置和清除页眉页脚。可在页面顶部和底部的左、中、右六个位置放置文本或页码。
以下示例接收已完成文档加载的 CPDFReaderView。页面索引从 0 开始,边距和字号使用 PDF 点(1 点为 1/72 英寸)。
import { CPDFReaderView } from '@compdfkit_pdf_sdk/react_native';
async function setHeaderFooter(reader: CPDFReaderView) {
const document = reader._pdfDocument;
const success = await document.updateHeaderFooter({
pages: [0],
margin: { left: 24, top: 24, right: 24, bottom: 24 },
slots: [
{ position: 'header_left', text: 'Document Review',
fontName: 'Helvetica', fontSize: 12, textColor: '#000000' },
{ position: 'footer_center', text: 'Page <<1>>', fontSize: 10 },
],
});
if (!success) throw new Error('更新页眉页脚失败');
if (!await reader.save()) throw new Error('保存文档失败');
}<<1>> 是页码占位符。position 支持 header_left、header_center、header_right、footer_left、footer_center 和 footer_right。同一位置只能出现一次;省略字体、字号和颜色时,默认使用 Helvetica、12 点和黑色。
updateHeaderFooter() 替换完整配置。修改已有内容时,应保留仍需使用的位置;空文本可用于清空某个位置。
import { CPDFReaderView } from '@compdfkit_pdf_sdk/react_native';
async function clearHeaderFooter(reader: CPDFReaderView) {
const document = reader._pdfDocument;
const current = await document.getHeaderFooter();
if (current === null) return;
if (!await document.clearHeaderFooter()) throw new Error('清除页眉页脚失败');
if (!await reader.save()) throw new Error('保存文档失败');
}getHeaderFooter() 在没有配置时返回 null。clearHeaderFooter() 清除整个文档的页眉页脚。更新和清除返回 boolean,参数错误或原生调用失败也可能使 Promise 拒绝,应由应用捕获并提示用户。