Flutter中如何为导出的PDF设置密码加密?
在Flutter中为导出的PDF添加密码保护
方法一:利用pdf包自带的PDF加密功能
你使用的pdf包3.8.1版本支持直接在生成PDF时设置密码保护,只需创建pw.Document实例时传入password参数,还能通过permissions控制文档操作权限(如禁止复制、打印等),生成的是标准加密PDF,兼容性更好。
修改你的代码如下:
import 'package:pdf/widgets.dart' as pw; import 'package:path_provider/path_provider.dart'; class PdfApi { static Future<File> generateCenteredText(String userPassword) async{ // 创建带密码保护的PDF文档 final pdf = pw.Document( password: userPassword, permissions: const pw.Permissions( copy: false, // 禁止复制内容 print: false, // 禁止打印 edit: false, // 禁止编辑 ), ); pdf.addPage(pw.Page( build: (context) => pw.Center( child: pw.Text('My PDF Content here...'), ), )); return saveDocument(name: 'Personal Records.pdf', pdf: pdf); } static Future<File> saveDocument({ required String name, required pw.Document pdf, }) async { final bytes = await pdf.save(); final dir = await getApplicationDocumentsDirectory(); final file = File('${dir.path}/$name'); await file.writeAsBytes(bytes); return file; } }
调用时传入用户设置的密码或PIN码即可:
await PdfApi.generateCenteredText('用户设置的密码或PIN');
方法二:用文件加密库对PDF文件整体加密
如果pdf包的加密逻辑无法满足需求,可使用encrypt库对生成的PDF文件进行整体加密,适合特定场景下的文件传输(注意:这种方式加密的文件不是标准加密PDF,接收方需用相同逻辑解密)。
- 在
pubspec.yaml添加依赖:
dependencies: encrypt: ^5.0.1
- 修改
saveDocument方法实现加密:
import 'package:pdf/widgets.dart' as pw; import 'package:path_provider/path_provider.dart'; import 'package:encrypt/encrypt.dart'; class PdfApi { static Future<File> generateCenteredText() async{ final pdf = pw.Document(); pdf.addPage(pw.Page( build: (context) => pw.Center( child: pw.Text('My PDF Content here...'), ), )); return saveDocument( name: 'Personal Records.pdf', pdf: pdf, password: '用户设置的密码或PIN' ); } static Future<File> saveDocument({ required String name, required pw.Document pdf, required String password, }) async { final bytes = await pdf.save(); // 生成加密密钥和初始化向量 final key = Key.fromUtf8(password.padRight(32, '0')); // 适配AES-256的32位密钥长度 final iv = IV.fromLength(16); final encrypter = Encrypter(AES(key, mode: AESMode.cbc)); // 加密PDF字节数据 final encryptedBytes = encrypter.encryptBytes(bytes, iv: iv).bytes; final dir = await getApplicationDocumentsDirectory(); final file = File('${dir.path}/$name'); await file.writeAsBytes(encryptedBytes); return file; } }
内容的提问来源于stack exchange,提问作者Bashar Al-shaibani
相关产品推荐
相关产品推荐

