Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Explore Flutter Encrypt & Decrypt PDF Files

Flutter is a portable UI toolkit. In other words, it’s a comprehensive app Software Development toolkit (SDK) that comes complete with widgets and tools. Flutter is a free and open-source tool to develop mobile, desktop, web applications. Flutter is a cross-platform development tool. This means that with the same code, we can create both ios and android apps. This is the best way to save time and resources in our entire process. In this, hot reload is gaining traction among mobile developers. Allows us to quickly see the changes implemented in the code with hot reload.

In this article, we will explore the Explore Flutter Encrypt &Decrypt PDF Files using the Syncfusion_flutter_pdf_file_package. With the help of the package, this user can encrypt and decrypt PDF documents in a flutter. So let’s get started.


Table Of Contents :

Encrypt and Decrypt PDF

Code Implement

Code File

Conclusion


Encrypt and Decrypt PDF :

Encrypt PDF files allows to protect the user from unauthorized access to PDF documents As data theft has become a big problem nowadays, it is necessary to secure the files before sending them to prevent unauthorized access to their data to the recipient. Happens if a PDF document is encrypted then we will decrypt it first to access its data content.

Provides two types of passwords to protect PDF files.

  • Document open password: Document Open Password Encrypts the PDF document with the user password that is required to open the PDF document.
  • Permission Passwords are used to limit access permissions to tasks such as printing, editing, and copying PDF document content

Implementation :

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies :

dependencies:
syncfusion_flutter_pdf: ^19.2.48-beta
open_file: ^3.0.1
path_provider: ^1.6.5

Step 2: Importing

import 'package:syncfusion_flutter_pdf/pdf.dart';
import ‘dart:io’;
import ‘package:open_file/open_file.dart’;
import ‘package:path_provider/path_provider.dart’;

Step 3: Enable AndriodX

org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

Code Implement :

Before explaining about encrypt and decrypt the pdf file, we will create a new dart file inside which we will take the column widget and create three different buttons inside it, on the click of each button it will show a different example.

Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed:securePdf, child: Text('Encrypt PDF'),
),

FlatButton(onPressed: securePdf, child: Text('Encrypt PDF')),
FlatButton(
onPressed: restrictPermissions,
child: Text('Restrict Permissions')),
FlatButton(onPressed: decryptPDF, child: Text('Decrypt PDF')),
]),

After defining the button we will first click on the button Encrypt PDF which onPressed has a defined method named securePDF() which loads the PDF document and opens the file of the PDF document in which it is saved.

Future<void> securePdf() async {
PdfDocument document = PdfDocument(
inputBytes: await _readDocumentData('credit_card_statement.pdf'));
document.security.userPassword = 'password@123';
List<int> bytes = document.save();
document.dispose();
_launchPdf(bytes, 'secured.pdf');
}

It has the _readDocumentData method which is used to read a PDF document of list type from the folder in which it is saved, the reference to the code below is included.

Future<List<int>> _readDocumentData(String name) async {
final ByteData data = await rootBundle.load('assets/$name');
return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
}

Now we will use the below code reference to get the directory path to launch the PDF document.

Future<void> _launchPdf(List<int> bytes, String fileName) async {
Directory directory = await getExternalStorageDirectory();
String path = directory.path;
File file = File('$path/$fileName');
await file.writeAsBytes(bytes, flush: true);
OpenFile.open('$path/$fileName');
}

Restrict PDF Permissions:

In Restrict PDF Permissions, you can customize the permissions to allow or restrict PDF documents. Like we can copy the content, edit the document, fill in the fields of the form it all lists the permission flags supported by this pdf library.

Include the following code to restrict the PDF document permissions.

PdfDocument document = PdfDocument(
inputBytes: await _readDocumentData('credit_card_statement.pdf'));
PdfSecurity security = document.security;
security.ownerPassword = 'owner@123';
security.permissions.addAll(<PdfPermissionsFlags>[
PdfPermissionsFlags.fullQualityPrint,
PdfPermissionsFlags.print,
PdfPermissionsFlags.fillFields,
PdfPermissionsFlags.copyContent
]);
//Save and dispose the document.
document.dispose();
_launchPdf(bytes, 'permissions.pdf');

Decrypt PDF:

Using flutter pdf library we can remove security from pdf documents password is required to decrypt pdf.

  • User password Removing from a PDF document: To remove open password in this we can do this by using the user password property available in the pdf security class.
PdfDocument document = PdfDocument(
inputBytes: await _readDocumentData('secured.pdf'),
password: 'owner@123');
PdfSecurity security = document.security;
security.userPassword = '';
  • User password Removing from a PDF document: In this, we can extract the password by using PDFSecurity class with the help of ownerPassword property available in it as given in the below code reference.
PdfDocument document = PdfDocument(
inputBytes: await _readDocumentData('secured.pdf'),
password: 'owner@123');
PdfSecurity security = document.security;
security.ownerPassword = '';

Code File :

import 'package:flutter/material.dart';

import 'package:flutter/services.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart';
import 'dart:io';
class EncryptDecryptPdfDemo extends StatefulWidget {

@override
_EncryptDecryptPdfDemoState createState() => _EncryptDecryptPdfDemoState();
}

class _EncryptDecryptPdfDemoState extends State<EncryptDecryptPdfDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
//title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed:securePdf, child: Text('Encrypt PDF'),
),

// FlatButton(onPressed: securePdf, child: Text('Encrypt PDF')),
FlatButton(
onPressed: restrictPermissions,
child: Text('Restrict Permissions')),
FlatButton(onPressed: decryptPDF, child: Text('Decrypt PDF')),
]),
),
);
}

Future<void> securePdf() async {
//Load the existing PDF document.
PdfDocument document = PdfDocument(
inputBytes: await _readDocumentData('credit_card_statement.pdf'));
//Set the document security.
document.security.userPassword = 'password@123';
//Save and dispose the document.
List<int> bytes = document.save();
document.dispose();
//Open the PDF file.
_launchPdf(bytes, 'secured.pdf');
}

Future<void> _launchPdf(List<int> bytes, String fileName) async {
//Get the external storage directory
Directory directory = await getExternalStorageDirectory();
//Get the directory path
String path = directory.path;
//Create an empty file to write the PDF data
File file = File('$path/$fileName');
//Write the PDF data
await file.writeAsBytes(bytes, flush: true);
//Open the PDF document in mobile
OpenFile.open('$path/$fileName');
}

Future<List<int>> _readDocumentData(String name) async {
final ByteData data = await rootBundle.load('assets/$name');
return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
}

Future<void> restrictPermissions() async {
//Load the existing PDF document.
PdfDocument document = PdfDocument(
inputBytes: await _readDocumentData('credit_card_statement.pdf'));
//Create document security.
PdfSecurity security = document.security;
//Set the owner password for the document.
security.ownerPassword = 'owner@123';
//Set various permission.
security.permissions.addAll(<PdfPermissionsFlags>[
PdfPermissionsFlags.fullQualityPrint,
PdfPermissionsFlags.print,
PdfPermissionsFlags.fillFields,
PdfPermissionsFlags.copyContent
]);
//Save and dispose the document.
List<int> bytes = document.save();
document.dispose();
//Open the PDF file.
_launchPdf(bytes, 'permissions.pdf');
}

Future<void> decryptPDF() async {
//Load the PDF document with permission password.
PdfDocument document = PdfDocument(
inputBytes: await _readDocumentData('secured.pdf'),
password: 'owner@123');
//Get the document security.
PdfSecurity security = document.security;
//Set owner and user passwords are empty string.
security.userPassword = '';
security.ownerPassword = '';
//Clear the security permissions.
security.permissions.clear();
//Save and dispose the document.
List<int> bytes = document.save();
document.dispose();
//Open the PDF file.
_launchPdf(bytes, 'unsecured.pdf');
}
}

Conclusion :

In this article, I have learned Encrypt and Decrypt PDF documents using the flutter pdf library in a Flutter application, which you can modify and experiment with according to your own, this little introduction was from the Encrypt and Decrypt PDF documents. In the Flutter demo from our side.

I hope this blog will provide you with sufficient information in Trying up the Encrypt and Decrypt PDF documents in a flutter. In Flutter in your flutter project. We showed you what the Encrypt and Decrypt PDF documents In Flutter are? and work on it in your flutter applications, So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

Feel free to connect with us
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Leave comment

Your email address will not be published. Required fields are marked with *.