PDF 生成模板编辑器
开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。
ComPDF Flutter SDK 自 3.2.0 起支持通过 CPDFDocument 管理页眉页脚。以下示例中的 document 为已打开的文档;使用阅读器时可通过 controller.document 获取。
import 'package:compdfkit_flutter/document/cpdf_document.dart';
import 'package:compdfkit_flutter/document/cpdf_header_footer.dart';
import 'package:flutter/material.dart';通过 updateHeaderFooter() 设置内容、位置和样式。pages 使用从 0 开始的页面索引,边距单位为 PDF 点(1/72 英寸)。
final pageCount = await document.getPageCount();
final success = await document.updateHeaderFooter(
CPDFHeaderFooter(
pages: List<int>.generate(pageCount, (index) => index),
margin: const EdgeInsets.all(36),
slots: const [
CPDFHeaderFooterSlot(
position: CPDFHeaderFooterPosition.headerLeft,
text: 'ComPDF',
fontName: 'Helvetica',
fontSize: 12,
),
CPDFHeaderFooterSlot(
position: CPDFHeaderFooterPosition.footerCenter,
text: 'Page <<1>>',
),
],
),
);
if (success) {
await document.save();
}<<1>> 为从 1 开始的页码占位符。CPDFHeaderFooterPosition 提供页眉和页脚的左、中、右六个位置;每个位置可分别设置 text、fontName、fontSize 和 textColor。
更新会替换六个位置的原有配置。需要保留的内容也应包含在 slots 中;使用空文本可清除指定位置的内容。
final current = await document.getHeaderFooter();
if (current != null) {
for (final slot in current.slots) {
debugPrint('${slot.position.name}: ${slot.text}');
}
}未设置页眉页脚时,读取结果为 null。修改时使用新的 CPDFHeaderFooter 调用 updateHeaderFooter(),成功后保存文档。
final cleared = await document.clearHeaderFooter();
if (cleared) {
await document.save();
}设置、修改和清除均作用于内存中的文档。使用 save() 保存原文件,或使用 saveAs() 输出副本,详见保存文档。