我在 Flutter 中开发了一项将个人联系人和数据导出为 PDF 的功能,我想在将数据导出到他/她的电子邮件时使用用户设置的密码或 PIN 码来保护该数据。一切都已设置并且工作正常,但我找不到为导出的 PDF 设置密码的方法。 这是我的小部件代码,我使用的是 PDF 包 3.8.1。
import 'package:pdf/widgets.dart' as pw;
import 'package:pdf/widgets.dart' show Font;
import 'package:pdf/widgets.dart' as pwFonts;
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
class PdfApi {
static Future<File> generateCenteredText() async{
final pdf = pw.Document();
pdf.addPage(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);
// secure the File with a PASSWORD or PIN code HERE....
return file;
}
}
我想要一种方法,在通过电子邮件发送文件之前,在 Flutter 中使用密码来加密/保护文件。
要使用来自syncfusion_flutter_pdf和pdf的包在Flutter中使用密码加密PDF,请按照以下步骤操作:
使用pdf包生成pdf并使用syncfusion_flutter_pdf设置密码 用于 pdf。
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:open_file/open_file.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart' as syncfusionPdf;
//Generate Uint8List of your pdf created using pdf package
final pdfBytes = await pdf.save();
await securePdfWithPassword(pdfBytes);
//Use the Below functions to set password by passing your generated pdf
//file to this function in Uint8List format
Future<void> securePdfWithPassword(List<int> pdfBytes) async {
//Load the existing PDF document.
syncfusionPdf.PdfDocument document = syncfusionPdf.PdfDocument(
inputBytes: pdfBytes,
);
document.security.userPassword = 'your_user_password';
document.security.ownerPassword = 'your_owner_password';
//Set the encryption algorithm.
document.security.algorithm =
syncfusionPdf.PdfEncryptionAlgorithm.aesx256Bit;
document.security.permissions.addAll([
syncfusionPdf.PdfPermissionsFlags.print,
syncfusionPdf.PdfPermissionsFlags.copyContent
]);
List<int> securedBytes = await document.save();
document.dispose();
//Save the file and launch/download.
saveAndLaunchFile(securedBytes, 'genrated_pdf.pdf');
}
//Save secured pdf and launch it
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
Directory directory = await getApplicationSupportDirectory();
String path = directory.path;
File file = File('$path/$fileName');
await file.writeAsBytes(bytes, flush: true);
//Open the secured Pdf File
OpenFile.open('$path/$fileName');
}