Skip to content

添加图片水印

ComPDF 支持 两种方式 添加图片水印

编程方式(API 调用)

dart
late CPDFReaderWidgetController _controller;

@override
Widget build(BuildContext context) {
  return Scaffold(
    resizeToAvoidBottomInset: false,
    appBar: AppBar(),
    body: Column(children: [
      TextButton(onPressed: () async {
        // 图像文件路径
        // 安卓平台支持 Uri 格式。
        // content://xxxx
        File imageFile = await extractAsset(context, 'images/logo.png');
        await controller.document.createWatermark(CPDFWatermark.image(
          imagePath: imageFile.path,
          opacity: 1,
          rotation: 45,
          pages: [0, 1, 2, 3],
          horizontalAlignment: CPDFWatermarkHorizontalAlignment.center,
          verticalAlignment: CPDFWatermarkVerticalAlignment.center,
        ));
      }, child: const Text('添加图片水印')),
      Expanded(child: CPDFReaderWidget(
        document: widget.documentPath,
        configuration: CPDFConfiguration(),
        onCreated: (controller) {
          setState(() {
            _controller = controller;
          });
        },
      ))
    ],));
}

UI 弹窗方式

  • CPDFConfiguration 中配置水印默认样式,例如图片、透明度、旋转角度。
  • 调用 controller.showAddWatermarkView(CPDFWatermarkConfig config) 打开添加水印的弹窗界面。
dart
// 在配置中设置默认图片水印样式
final configuration = CPDFConfiguration(
  globalConfig: const CPDFGlobalConfig(
    watermark: CPDFWatermarkConfig(
      image: 'ic_logo'
      opacity: 120,
      rotation: -45
    )
  )
);

// 打开添加水印弹窗
controller.showAddWatermarkView(
  config:
  CPDFGlobalConfig(
    watermark: CPDFWatermarkConfig(
      image: 'ic_logo'
      opacity: 120,
      rotation: -45
    )
  )
);

要自定义默认的图片,您需要在Android和iOS中以不同的方式实现它们。

Android

  1. 将图片文件添加到资源文件中
shell
android/app/src/main/res/drawable/ic_logo.png
  1. 使用不带扩展名的文件名在代码中引用它们:
dart
image: 'ic_logo'

iOS

  1. 将图片文件通过Xcode导入到项目中
guides_flutter_3.7.4_1
  1. 使用不带扩展名的文件名在代码中引用它们:
dart
image: 'ic_logo'

Flutter 跨平台方案

也可以直接将图片资源放入 Flutter 项目中,然后在运行时复制到设备本地存储,再传入图片的文件路径:

dart
final imagePath = await extractAsset(context, 'images/ic_logo.png');
await controller.showAddWatermarkView(
  config: CPDFWatermarkConfig(
    image: imagePath.path,
    rotation: -45,
    opacity: 200,
    scale: 2.0
  ),
);