How to externally sign a PDF document using Flutter?
The Flutter PDF library is used to create, read, and edit PDF documents programmatically without Adobe dependencies. Using this library, you can externally sign a PDF document using Flutter.
Steps to externally sign a PDF document programmatically
-
Create a new Flutter application project.
- Open Visual Studio Code (after installing the Dart and Flutter extensions as stated in this setup editor page).
- Click View -> Command Palette.
- Type Flutter and choose Flutter: New Project.
- Enter the project name and press Enter.
- Now, choose the location of the project.
-
Add the following code in your pubspec.yaml file to install the syncfusion® flutter pdf package in your application. It will be automatically downloaded from Pub once you trigger the Flutter pub get command or the Get packages option from Visual Studio Code.
dependencies:
syncfusion_flutter_pdf: ^25.1.39
x509: ^0.2.4+2
- Import the following package into your main.dart file.
import 'package:syncfusion_flutter_pdf/pdf.dart';
- Create a new Dart file named pdf_external_signer.dart under the lib folder and import the following packages in it.
import 'package:flutter/services.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart';
import 'package:x509/x509.dart' as x509;
- Include the following code sample in the pdf_external_signer.dart file.
class PdfExternalSigner extends IPdfExternalSigner {
// Hash algorithm.
@override
DigestAlgorithm get hashAlgorithm => DigestAlgorithm.sha256;
@override
Future<SignerResult> sign(List<int> message) async {
// Read the private key.
final pem = await _readData('privatekey.pem');
final x509.KeyPair keyPair =
x509.parsePem(String.fromCharCodes(pem)).single;
final privateKey = keyPair.privateKey as x509.RsaPrivateKey;
final signer = privateKey.createSigner(x509.algorithms.signing.rsa.sha256);
// Sign the document hash.
final x509.Signature signed = signer.sign(message);
return SignerResult(signed.data.toList());
}
Future<List<int>> _readData(String name) async {
final ByteData data = await rootBundle.load('assets/$name');
return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
}
}
- Add the following code in the lib/main.dart file to create a simple button.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(onPressed: signPdf, child: const Text('Sign PDF')),
],
),
),
);
}
- Include the following code sample in the signPdf method to externally sign a PDF document.
Future<void> signPdf() async {
// Load the existing PDF document.
PdfDocument loadedDocument =
PdfDocument(inputBytes: await _readData('Input.pdf'));
// Get the first page.
PdfPage page = loadedDocument.pages[0];
// Create a PDF signature field.
PdfSignatureField signatureField = PdfSignatureField(page, 'SignatureField',
bounds: const Rect.fromLTWH(0, 0, 200, 100));
// Set the signature field properties.
signatureField.signature = PdfSignature()
..addExternalSigner(
PdfExternalSigner(), [await _readData('certificate.cer')]);
// Add the signature field to the document.
loadedDocument.form.fields.add(signatureField);
// Save the document.
List<int> bytes = await loadedDocument.save();
// Dispose of the document.
loadedDocument.dispose();
// Save the file and launch/download.
SaveFile.saveAndLaunchFile(bytes, 'output.pdf');
}
- Use the following code to load the PDF file in the Flutter project.
a. Add the following code to your pubspec.yaml file.
flutter:
# To add assets to your application, add an assets section, like this:
assets:
- assets/
b. Import the following package in your main.dart file.
import 'package:flutter/services.dart';
c. Add the following code in the lib/main.dart file to read the existing PDF file.
Future<List<int>> _readData(String name) async {
final ByteData data = await rootBundle.load('assets/$name');
return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
}
- Follow these steps to launch the generated PDF file on desktop, mobile, and web platforms.
Web
a. Add the web package as a dependency in your pubspec.yaml file. Then, create a new Dart file named save_file_web.dart. Finally, add the following code to implement the file download functionality using the web package.
import 'dart:convert';
import 'package:web/web.dart' as web;
b. To enable file saving and initiate downloads in a Flutter web environment, use the following code within the saveAndLaunchFile method.
// Function to save and launch a file for download in a web environment.
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
final web.HTMLAnchorElement anchor =
web.document.createElement('a') as web.HTMLAnchorElement
..href = "data:application/octet-stream;base64,${base64Encode(bytes)}"
..style.display = 'none'
..download = fileName;
// Insert the new element into the DOM.
web.document.body!.appendChild(anchor);
// Initiate the download.
anchor.click();
// Clean up the DOM by removing the anchor element.
web.document.body!.removeChild(anchor);
}
Desktop and mobile:
a. Add the following dependencies in your pubspec.yaml file.
open_file: ^3.2.1
path_provider: ^2.0.11 # Open-source library to launch the PDF file on mobile devices
b. Create a new Dart file named save_file_mobile_and_desktop.dart under the lib folder and import the following packages in save_file_mobile_and_desktop.dart file.
import 'dart:io';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
c. Include the following code snippet in save_file_mobile_and_desktop.dart to open a PDF document on Desktop and Mobile.
class SaveFile {
static Future<void> saveAndLaunchFile(
List<int> bytes, String fileName) async {
// Get external storage directory.
Directory directory = await getApplicationSupportDirectory();
// Get 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 a PDF document on mobile.
OpenFile.open('$path/$fileName');
}
}
- Run the sample using the flutter run command. After the application launches, you will get a PDF document as follows.
A complete working sample can be downloaded from externally_sign_a_PDF.zip.
Take a moment to peruse the documentation, where you will find other options such as adding a digital signature, externally signing a PDF document, adding signature validation, adding a timestamp to a PDF document, retrieving certificate details from an existing PDF, enabling LTV signature, digital signature with customization, and digital signature validation.
Click here to explore the rich set of Syncfusion Essential® PDF features.
Conclusion
I hope you enjoyed learning about how to externally sign a PDF document using Flutter.
You can refer to our Flutter PDF feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Flutter PDF example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums or feedback portal. We are always happy to assist you!