咨询Flutter中填充PDF可填写表单的免费库及实现方法
免费Flutter PDF可填写表单填充方案
以下是两个免费开源的库及具体实现方式,可替代收费的pdftron和syncfusion:
1. 使用 pdf 库(dart_pdf)
这是纯Dart编写的开源PDF库,支持创建、编辑PDF表单字段,完全免费且无使用限制。
实现步骤
- 添加依赖到
pubspec.yaml:
dependencies: pdf: ^3.10.0 path_provider: ^2.1.1 intl: ^0.18.1 # 可选,用于格式化时间
- 核心填充代码:
import 'dart:io'; import 'package:pdf/pdf.dart'; import 'package:pdf/widgets.dart' as pw; import 'package:path_provider/path_provider.dart'; import 'package:intl/intl.dart'; Future<void> fillPdfForm() async { // 获取本地存储路径 final dir = await getApplicationDocumentsDirectory(); final inputFile = File('${dir.path}/your_template.pdf'); // 替换为你的源PDF表单路径 final outputFile = File('${dir.path}/filled_form.pdf'); // 加载现有PDF文档 final pdfDoc = pw.Document(); final pages = await pdfDoc.loadFromPath(inputFile.path); // 遍历页面填充字段 for (final page in pages) { // 填充系统时间到指定字段(假设字段名为"current_time") final timeField = page.annotations.firstWhere( (anno) => anno is pw.TextFormFieldAnnotation && anno.name == 'current_time', orElse: () => null, ) as pw.TextFormFieldAnnotation?; if (timeField != null) { // 格式化系统时间为指定格式 final formattedTime = DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now()); timeField.text = formattedTime; } // 填充其他示例字段 final nameField = page.annotations.firstWhere( (anno) => anno is pw.TextFormFieldAnnotation && anno.name == 'username', orElse: () => null, ) as pw.TextFormFieldAnnotation?; nameField?.text = 'Test User'; } // 保存填充后的PDF await outputFile.writeAsBytes(await pdfDoc.save()); }
2. 使用 flutter_pdfbox 插件
基于Apache PDFBox(开源Java PDF工具库)的Flutter包装,支持完整的PDF表单操作,适合复杂表单场景。
实现步骤
- 添加依赖到
pubspec.yaml:
dependencies: flutter_pdfbox: ^0.1.0 path_provider: ^2.1.1 intl: ^0.18.1
- 核心填充代码:
import 'dart:io'; import 'package:flutter_pdfbox/flutter_pdfbox.dart'; import 'package:path_provider/path_provider.dart'; import 'package:intl/intl.dart'; Future<void> fillPdfWithPdfBox() async { final dir = await getApplicationDocumentsDirectory(); final inputPath = '${dir.path}/your_template.pdf'; final outputPath = '${dir.path}/filled_form.pdf'; // 打开PDF文档 final doc = await FlutterPdfBox.openDocument(inputPath); // 填充系统时间字段 final formattedTime = DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now()); await doc.fillFormField('current_time', formattedTime); // 填充其他字段 await doc.fillFormField('email', 'test@example.com'); // 保存并关闭文档 await doc.save(outputPath); await doc.close(); }
关键注意事项
- 提前确认PDF表单中每个字段的名称(可通过Adobe Acrobat等工具查看字段属性获取)。
- Android需配置文件读写权限,iOS需在
Info.plist中添加文件访问权限描述。 - 若需处理复杂表单(如复选框、下拉框),
flutter_pdfbox支持更多字段类型的操作,可参考其API文档。
内容的提问来源于stack exchange,提问作者user23347281
相关产品推荐
相关产品推荐

