You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter的PSPDFKit中为PDF添加图片注释?

用PSPDFKit在Flutter中添加图片注释的实现方案

核心实现思路

PSPDFKit Flutter端可通过AnnotationManager创建图片注释,本质是实例化StampAnnotation并绑定图片资源,再将其添加到目标PDF文档中。

完整代码示例

1. 配置图片资源

先将目标图片放入项目资源目录(如assets/images/),并在pubspec.yaml中声明资源路径:

flutter:
  assets:
    - assets/images/your_image.png

2. 添加图片注释的核心逻辑

import 'package:flutter/services.dart';
import 'package:pspdfkit_flutter/pspdfkit_flutter.dart';

// 传入PSPDFKit控制器和文档路径,执行添加图片注释操作
Future<void> addImageAnnotation(PspdfkitViewController controller, String documentPath) async {
  // 从资源目录加载图片为字节数据
  final ByteData imageData = await rootBundle.load('assets/images/your_image.png');
  final Uint8List imageBytes = imageData.buffer.asUint8List();

  // 构建图片注释实例
  final annotation = StampAnnotation(
    pageIndex: 0, // 目标页码,从0开始计数
    bounds: Rect.fromLTWH(100, 100, 200, 150), // 注释的位置与尺寸:左偏移、上偏移、宽度、高度
    image: imageBytes,
    // 可选属性:调整透明度、可编辑性等
    opacity: 1.0,
    isEditable: true,
  );

  // 获取文档的注释管理器并添加注释
  final annotationManager = await PSPDFKit.getAnnotationManagerForDocument(documentPath);
  await annotationManager.addAnnotation(annotation);

  // 刷新视图确保注释显示
  await controller.reloadDocument();
}

3. 在PSPDFKit视图中调用

在PDF视图初始化完成后触发添加操作:

PspdfkitView(
  documentPath: 'path/to/your/target.pdf',
  onCreated: (PspdfkitViewController controller) async {
    await addImageAnnotation(controller, 'path/to/your/target.pdf');
  },
)

关键注意事项

  • 支持PNG、JPG等常见图片格式,需确保资源路径与pubspec.yaml配置一致
  • 若需动态调整注释位置,可通过PSPDFKit.getPageSize(documentPath, pageIndex)获取页面尺寸后计算bounds参数
  • 如果要从相册选择图片,可集成image_picker插件获取图片字节数据,替换上述rootBundle加载逻辑

内容的提问来源于stack exchange,提问作者Farooq Tariq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 13:50:03