PDF 生成模板编辑器
开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。
ComPDF Flutter SDK 自 3.2.0 起支持设置颜色或图片背景。背景属于 PDF 文档内容,与阅读器的显示主题分别配置。
以下示例中的 document 为已打开的 CPDFDocument。
import 'package:compdfkit_flutter/document/cpdf_background.dart';
import 'package:flutter/material.dart';final pageCount = await document.getPageCount();
final pages = List<int>.generate(pageCount, (index) => index);
final success = await document.updateBackground(
CPDFBackground.color(
pages: pages,
color: Colors.amber,
opacity: 0.2,
allowView: true,
allowPrint: true,
),
);
if (success) {
await document.save();
}imagePath 使用可读取的本地图片路径。以下示例中的 pages 为目标页面索引列表。
final success = await document.updateBackground(
CPDFBackground.image(
pages: pages,
imagePath: '/path/to/background.png',
opacity: 0.35,
scale: 1.0,
rotation: 0,
),
);
if (success) {
await document.save();
}| 参数 | 说明 |
|---|---|
pages | 非空的页面索引列表,从 0 开始 |
opacity | 透明度,范围为 0~1 |
scale | 缩放比例,必须大于 0 |
rotation | 旋转角度,范围为 0~360 |
horizontalAlignment、verticalAlignment | 水平、垂直对齐方式,默认居中 |
horizontalOffset、verticalOffset | 水平、垂直偏移 |
allowView、allowPrint | 是否在查看、打印时显示,默认均为 true |
final background = await document.getBackground();
if (background != null) {
debugPrint('Type: ${background.type.name}');
debugPrint('Opacity: ${background.opacity}');
}没有背景时返回 null。已有图片背景的源图片路径无法从 PDF 中恢复,返回对象的 imagePath 为 null;更新图片背景时需重新提供本地图片路径。读取的 pages 可能为空,更新时应由应用明确指定目标页面。
修改背景时,构造新的 CPDFBackground 并再次调用 updateBackground()。
final cleared = await document.clearBackground();
if (cleared) {
await document.save();
}所有更改均需通过 save() 或 saveAs() 保存到文件。