How to Encrypt and Decrypt PDF Files in Flutter | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (172).NET Core  (29).NET MAUI  (192)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (209)BoldSign  (12)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (63)Flutter  (131)JavaScript  (219)Microsoft  (118)PDF  (80)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (882)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (49)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (125)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (62)Development  (613)Doc  (7)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (37)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (488)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (41)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (368)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (30)Visual Studio Code  (17)Web  (577)What's new  (313)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
How to Encrypt and Decrypt PDF Files in Flutter

How to Encrypt and Decrypt PDF Files in Flutter

The Syncfusion Flutter PDF Library now allows users to encrypt and decrypt PDF documents in Flutter applications.

PDF encryption allows users to protect their PDF documents from unauthorized access. These days, data theft has become a real problem. So, we need to secure important files before sending them to recipients to prevent unauthorized access to their content. And then, if a PDF document we receive is encrypted, we have to decrypt it to access its content.

There are two types of passwords that are available to protect PDF files:

  • Document open password: Most PDF documents are encrypted with a user password that is required to open the documents.
  • Permission password: A permission password, also known as an owner password, is used to limit the access permissions to various operations such as printing, editing, and copying content in a PDF document.

With the Syncfusion Flutter PDF Library, you can protect your PDF documents with either of these passwords, or both.

If a PDF is encrypted with both types of passwords, you can use either of the passwords to open it. But to change the restricted features, you need the permission password.

In this blog, I will show you how to encrypt and decrypt PDF files, divided into the following topics:

Experience a leap in PDF technology with Syncfusion's PDF Library, shaping the future of digital document processing.

Encrypt a PDF document

The Syncfusion Flutter PDF Library provides support for basic (RC4) to advanced (AES) encryption standards. The following are the encryption standards supported:

  • RC4 40-bit
  • RC4 128-bit
  • AES 128-bit
  • AES 256-bit
  • AES 256-bit Revision 6

Following are the steps to encrypt a PDF document using Syncfusion Flutter PDF Library.

Step #1: Create a Flutter application

Follow the instructions provided in this Get Started documentation to create a basic project in Flutter.

Step #2: Add Syncfusion Flutter PDF dependency

Include the Syncfusion Flutter PDF package dependency in the pubspec.yaml file in your project.

dependencies:
  syncfusion_flutter_pdf: ^18.4.30-beta

Step #3: Get the packages

Run the following commands to get the required packages.

$ flutter pub get

Step #4: Import the package

Import the PDF package into the main.dart file, as shown in the following code example.

import 'package:syncfusion_flutter_pdf/pdf.dart';

Step #5: Encrypt PDF file

  1. Add a Button widget as a child to the container widget.
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              FlatButton(
                child: Text(
                  'Encrypt PDF',
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: _extractText,
                color: Colors.blue,
              )
            ],
          ),
        ),
      );
    }
  2. Include the following code in the button-click event to secure the PDF file.
    //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();
  3. To access the PDF document, set the input document in the assets section of the pubspec.yaml file, as shown in the following. Here, the documents are placed inside the assets  folder.
    # To add assets to your application, add an assets section, like this:
    assets:
      - assets/credit_card_statement.pdf
      - assets/secured.pdf

    Include the following code to read the PDF document from the folder where it is saved.

    Future<List<int>> _readDocumentData(String name) async {
      final ByteData data = await rootBundle.load('assets/$name');
      return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    }
    
  4. Include the following code to launch the secured PDF file.a.  Add the following package dependencies in the pubspec.yaml file in your project.
    open_file: ^3.0.1
    path_provider: ^1.6.5

    b. Import the following packages in your main.dart file.

    import 'dart:io';
    import 'package:open_file/open_file.dart';
    import 'package:path_provider/path_provider.dart';

    c. Include the following code to launch the output PDF document.

    //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/secured.pdf');
    //Write the PDF data.
    await file.writeAsBytes(bytes, flush: true);
    //Open the PDF document in mobile.
    OpenFile.open('$path/secured.pdf');

    By executing the program, you will get output like the following.

    Encrypt PDF file

    You can also set both the user and owner passwords by using the following code.

    //Create document security.
    PdfSecurity security = document.security;
    //Set the owner password for the document.
    security.ownerPassword = 'Owner@123';
    //Set the user password for the document.
    security.userPassword = 'password@123';

Explore the wide array of rich features in Syncfusion's PDF Library through step-by-step instructions and best practices.

Restrict PDF permissions

You can customize the permissions to allow or restrict certain actions on PDFs, such as:

  • Copying content
  • Printing
  • Editing the document
  • Filling form fields

The following table lists the permission flags supported by Syncfusion Flutter PDF Library.

Permission flagDescription
accessibilityCopyContentEnables content screen reading for users with disabilities.
assembleDocumentAllows users to manipulate the pages in the document.
copyContentAllows users to copy content from the document.
editAnnotationsAllows users to get user input or feedback on a document.
editContentAllows users to edit the content in the document.
fillFieldsAllows users to fill out and sign a form.
fullQualityPrintAllows users to print a clear copy of the document.
printAllows users to print the document with low quality.

Note: Only access to the included flags will be enabled and all other permissions will be disabled.

There are also permissions that are interrelated, so enabling one will affect another:

  • Enabling copyContent will enable accessibilityCopyContent, as well.
  • Enabling editContent will enable assembleDocument, as well.
  • Enabling editAnnotation will enable fillFields, as well.
  • fullQualityPrint will not work without enabling print.

To restrict PDF permissions, you must set the permission password (owner password) for the PDF document. You can set the owner password by using the ownerPassword property available in the PdfSecurity class.

You can set various permissions for the PDF document using the Permissions property available in the PdfSecurity class.

Include the following code to restrict the PDF document permissions.

//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 permissions.
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);

By executing the program, you will get an output document like the following.
Customize PDF permissions

Witness the advanced capabilities of Syncfusion's PDF Library with feature showcases.

Decrypt or removing security from PDF

You can remove the security from the PDF document by using Syncfusion Flutter PDF Library, making it available for editing. It requires the password to decrypt the PDF document.

  1. Removing the user password from a PDF document: You can remove the document open password by using the userPassword property available in the PdfSecurity class.
    //Load the PDF document with user or 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 to empty.
    security.userPassword = '';
  2. Removing the owner password from the PDF document: You can remove the permission password by using the ownerPassword property available in the PdfSecurity class. The following code illustrates this.
    //Load the PDF document with permission password (since the user password cannot be used to alter the security permissions).
    PdfDocument document = PdfDocument(
        inputBytes: await _readDocumentData('secured.pdf'),
        password: 'owner@123');
    //Get the document security.
    PdfSecurity security = document.security;
    //Set owner and user passwords to empty.
    security.ownerPassword = '';
  3. Remove both the user and owner passwords from the PDF document:
    a. Load the PDF document using the owner (permission) password (since the user password cannot be used to alter the security permissions).
    b. Set the owner and user password properties to empty string.
    c. Clear the security permissions by using the clear method available in the PdfPermissions class.
    d. Save the document.
  4. The following code example illustrates this.
    //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 to 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');

    By executing this code, you will get an output document like the following screenshot.
    Decrypt PDF document

Resource

You can check out the sample from the following GitHub repository on encrypting and decrypting PDF documents.

Syncfusion’s high-performance PDF Library allows you to create PDF documents from scratch without Adobe dependencies.

 Conclusion

In this blog post, we have learned the steps to encrypt and decrypt PDF documents using the Syncfusion Flutter PDF Library in a Flutter application.

Take a moment to peruse our documentation, where you’ll find other options and features, all with accompanying code examples.

If you have any questions about these features, please let us know in the comments below. You can also contact us through our support forum, support portal, or feedback portal. We are happy to assist you!

If you liked this article, we think you would also like the following articles about PDF Library:

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed
Scroll To Top