Skip to content
DemoFAQ

PDF 生成模板编辑器

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

查看 GitHub
Flutter Guides Background

文档背景 ​

ComPDF Flutter SDK 自 3.2.0 起支持设置颜色或图片背景。背景属于 PDF 文档内容,与阅读器的显示主题分别配置。

以下示例中的 document 为已打开的 CPDFDocument。

dart
import 'package:compdfkit_flutter/document/cpdf_background.dart';
import 'package:flutter/material.dart';

设置颜色背景 ​

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 为目标页面索引列表。

dart
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

读取与更新背景 ​

dart
final background = await document.getBackground();
if (background != null) {
  debugPrint('Type: ${background.type.name}');
  debugPrint('Opacity: ${background.opacity}');
}

没有背景时返回 null。已有图片背景的源图片路径无法从 PDF 中恢复,返回对象的 imagePath 为 null;更新图片背景时需重新提供本地图片路径。读取的 pages 可能为空,更新时应由应用明确指定目标页面。

修改背景时,构造新的 CPDFBackground 并再次调用 updateBackground()。

清除背景 ​

dart
final cleared = await document.clearBackground();
if (cleared) {
  await document.save();
}

所有更改均需通过 save() 或 saveAs() 保存到文件。