The PDF ( Portable Document Format) package is a file format . software technology that enables reliable electronic document exchange and display regardless of software, hardware and operating system. For many , different things, including electronic books, forms, manuals and PDF files are more used.
Programmers can create, edit, view and share PDF files with the use of the features and tools provided by the flutter PDF package.
Developers can work with PDF files in their Flutter applications thanks to the PDF package for Flutter, which is a collection of libraries. Developers can add annotations, images, and other components to PDF documents as well as create, read, and edit PDF files using the PDF package. Additionally, the package contains tools for rendering PDF files in Flutter programmers and for supporting zooming, panning, and scrolling inside PDF files. The PDF package for Flutter is a complete solution for working with PDF files in Flutter applications because it also supports security features like passwords and encryption.
Step 1): Configuring our pubspec.yaml
pdf: ^any
Step 2): installing the package
flutter pub get
Step 3): import the file
import 'package:pdf/pdf.dart';
Using the tools or features offered by the flutter PDF package, users can create, edit, view, and share PDF files. Several significant features of the PDF package include:
Creation of PDF files:
The library enables programmers to create new PDF files , add pages with different page formats (like A4 size ), and embellish the pages with widgets like text, images, tables and charts etc.
/// Create a new PDF file
final pdf = pw.Document();
/// Add a new page in to the PDF document
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
return pw.Center(
child: pw.Text("PDF package explanation", style: pw.TextStyle(fontSize: 24)),
);
},
),
);
// Save the PDF document to disk
final bytes = await pdf.save();
final file = File('output.pdf');
await file.writeAsBytes(bytes);
With the help of the pdf library this code creates a new PDF file, adds a page, changes the page format to A4 size adds a centered text widget to the page and then save the PDF file to local storage under the name “pdfName.pdf.” In addition to supporting the addition of images, tables, charts, and annotations as well as fonts, colors, and styles, the pdf library provides many more features for working with PDF files.
Editing of PDF files:
// Open an existing PDF file
final bytes = File('input.pdf').readAsBytesSync();
final pdf = pw.Document().loadFromBytes(bytes);
// Get the first page of the PDF file
final page = pdf.pages[0];
// Modify the text on the first page of the PDF file
page.addText(
pw.Text(
'Modified text',
style: pw.TextStyle(fontSize: 24),
),
);
// Save the modified PDF file to disk
final modifiedBytes = await pdf.save();
final modifiedFile = File('output.pdf');
await modifiedFile.writeAsBytes(modifiedBytes);
This code retrieves the first page of an existing PDF file from storage using the pdf library , modifies the text on that page and then saves the modified PDF file to storage with the name pdfName .pdf extention . The pdf library offers tools for adding and editing images, tables and annotations highlights , underlines etc…… as well as support for changing the font, color, and style.
Conversion of PDF files:
The Flutter pdf package also includes tools for converting PDF files to other formats like image, HTML or text etc…… Here is an example of code that turns a PDF file into an image using the pdf library:
/// Open an existing PDF file here
final bytes = File('input.pdf').readAsBytesSync();
final pdf = pw.Document().loadFromBytes(bytes);
/// Convert the PDF file to an image format
final image = await pdf.asImage(
format: PdfPageFormat.a4,
dpi: 300,
);
/// Save the image to storage
final pngBytes = await image.pngBytes;
final pngFile = File('output.png');
await pngFile.writeAsBytes(pngBytes);
The user can choose a PDF file have it converted file to an image and then see the image as a result of their selection in this code definition of a Flutter application with a single page. The PDF file is converted to a PNG image using the pdf library as Image method the result image is saved to a temporary directory in local storage before being shown in the application .
Security features:
A number of security features are offered by the pdf package in Flutter to guard against unauthorized access and modification of PDF files. Encryption, password protection, and digital signatures are some of these security features.
Here show example of how to use Flutter pdf library to encrypt and password-protect a PDF file in flutter application :
To prevent unauthorized access, you can encrypt a PDF file with a password. An extensively used encryption standard, 128-bit AES encryption, is supported by the package.
pdf file can have set various levels of permissions including printing , copying , editing, annotating etc . Both the user and the file owner can receive these permissions individually.
final _formKey = GlobalKey<FormState>();
final _passwordController = TextEditingController();
final _pdfController = TextEditingController();
File _pdfFile;
Future<void> _encryptPdf() async {
// Open the PDF file
final bytes = await _pdfFile.readAsBytes();
final pdf = pw.Document().loadFromBytes(bytes);
// Get the encryption parameters from the form
final password = _passwordController.text;
final userPerms = pw.Permissions(
canPrint: true,
canCopy: true,
canModify: false,
canAnnotate: true,
);
final ownerPerms = pw.Permissions(
canPrint: true,
canCopy: true,
canModify: true,
canAnnotate: true,
);
// Encrypt the PDF file with the specified password and permissions
pdf.encrypt(
userPassword: password,
userPermissions: userPerms,
ownerPassword: password,
ownerPermissions: ownerPerms,
);
// Save the encrypted PDF file to disk
final directory = await getTemporaryDirectory();
final encryptedFile = File('${directory.path}/encrypted.pdf');
await encryptedFile.writeAsBytes(pdf.save());
// Display a dialog with the location of the encrypted file
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('PDF encrypted'),
content: Text('The encrypted PDF file is located at:\n\n${encryptedFile.path}'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'),
),
],
),
);
}
Annotation tools:
To highlight or annotate PDF documents, a variety of annotation tools are available in the Flutter PDF package. Several of the annotating tools included in the PDF package are as follows:
late PDFViewController _pdfViewController;
void _addAnnotation() async {
final page = await _pdfViewController.getCurrentPage();
final point = await _pdfViewController.getPoint();
await _pdfViewController.addTextAnnotation(
page!,
point!,
"This is an example of a text annotation.",
);
}
OCR (Optical Character Recognition):
Text in scanned images or PDF files can be easily edited and searched thanks to OCR (Optical Character Recognition) technology. Using OCR, you can extract text from a PDF file for purposes such as editing, copying, and searching.
Here are the fundamental actions you can take:
1): Open the PDF file and read its content into a byte buffer using the Flutter dart:io library.
2): To extract the text from the PDF byte buffer, use a PDF parsing library like pdf or dart_pdf.
3): Remove any extraneous characters or formatting from the extracted text, such as page numbers, headers, and footers.
4): Depending on your needs, return the processed text as a string or list of strings.
To help you get started, here is some sample code:
import 'dart:io';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pdfwidgets;
void main() {
/// Open the PDF file
final file = File('path/to/pdf/file.pdf');
final bytes = file.readAsBytesSync();
/// Parse the PDF and extract the text
final pdf = PdfDocument.openBytes(bytes);
final pages = pdf.pages.map((page) => page.text).toList();
/// Process the extracted text
final processedPages = pages.map((page) {
/// Remove any unwanted characters or formatting
return page.replaceAll('\n', '').trim();
}).toList();
/// Print the processed text
print("processedPages :: $processedPages");
}
Form filling and signing:
For many applications, the ability to fill out and sign forms in PDF files is a crucial component. Flutter’s PDF package includes tools for electronically filling out and signing PDF forms. This package makes it simple to create PDF forms, fill them out with user input, and add a digital signature. Checkboxes, radio buttons, and other form elements can also be added to PDF forms with the help of this package.
pdf.addPage(pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Center(
child: pw.Form(
child: pw.Column(
children: [
pw.Text('Name:'),
pw.TextField(),
pw.SizedBox(height: 20),
pw.Text('Age:'),
pw.TextField(),
pw.SizedBox(height: 20),
pw.Text('Gender:'),
pw.RadioButtonGroup(
options: ['Male', 'Female'],
),
pw.SizedBox(height: 20),
pw.Text('Country:'),
pw.DropDown(
items: ['USA', 'Canada', 'Mexico'],
),
pw.SizedBox(height: 20),
pw.Text('Comments:'),
pw.TextField(),
],
),
),
);
}
));
Signature field can added using the pw.Signature widget provided by the pdf package.
pdf.addPage(pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Center(
child: pw.Form(
child: pw.Column(
children: [
pw.Text('Name:'),
pw.TextField(),
pw.SizedBox(height: 20),
pw.Text('Age:'),
pw.TextField(),
pw.SizedBox(height: 20),
pw.Text('Gender:'),
pw.RadioButtonGroup(
options: ['Male', 'Female'],
),
pw.SizedBox(height: 20),
pw.Text('Country:'),
pw.DropDown(
items: ['USA', 'Canada', 'Mexico'],
),
pw.SizedBox(height: 20),
pw.Text('Comments:'),
pw.TextField(),
pw.SizedBox(height: 20),
pw.Text('Signature:'),
pw.Signature(),
],
),
),
);
}
));
to obtain this example code, click here….
Conclusion
The PDF package can be used to create apps that run on both Android and iOS platforms making the development of cross platform software simple . The package includes support for multicolumn layouts , headers and footers and custom page sizes among other layout options for working with PDF files. Due to the package’s fast and effective PDF rendering capabilities, working with large PDF files doesn’t have to compromise performance.
Here is a brief description of a pdf package; modify it to suit your needs.
Thanks for reading this article…..
Have a beautiful day……