How to add bookmarks in a PDF using Syncfusion Flutter PDF?
A bookmark is a type of link with representative text in the navigation panel. Each bookmark goes to a different view or page in the document. The Flutter PDF library allows you to add bookmarks with different styles in a PDF using Flutter.
Steps to add bookmarks to a PDF document programmatically
- Create a new Flutter application project.
1.1. Open Visual Studio Code (after installing the Dart and Flutter extensions as stated in this setup editor page)
1.2. Click View -> Command Paletteā¦
1.3. Type Flutter and choose Flutter: New Project.
1.4. Enter the project name and press the Enter button.
1.5. 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 the pub once you trigger the flutter pub get a comment or Get packages option from the Visual Studio Code.
dependencies: syncfusion_flutter_pdf: ^20.3.49
Import the following package in your main.dart file.
import 'package:syncfusion_flutter_pdf/pdf.dart';
- Add the following code in the lib/main.dart file to create a simple button.
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextButton( child: Text( 'Create sample', style: TextStyle(color: Colors.white), ), style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith( (states) => Colors.blue)), onPressed: _addBookmarksToPDF, ) ], ), ), ); }
- Add the following code to the _addBookmarksToPDF function to add bookmarks to the PDF document programmatically.
Future<void> _addBookmarksToPDF() async { // Create a new document PdfDocument document = PdfDocument(); // Add a page PdfPage page = document.pages.add(); // Create a bookmark PdfBookmark bookmark = document.bookmarks.add('Chapter 1'); // Set the destination page and location bookmark.destination = PdfDestination(page, Offset(10, 10)); // Draw the content on the PDF page page.graphics.drawString( 'Chapter1', PdfStandardFont(PdfFontFamily.helvetica, 10), brush: PdfBrushes.red, bounds: Rect.fromLTWH(10, 10, 0, 0)); // Add a child bookmark PdfBookmark childBookmark = bookmark.insert(0, 'Section 1'); childBookmark.destination = PdfDestination(page, Offset(30, 30)); // Draw the content on the PDF page page.graphics.drawString( 'Section1', PdfStandardFont(PdfFontFamily.helvetica, 10), brush: PdfBrushes.green, bounds: Rect.fromLTWH(30, 30, 0, 0)); // Set the text style and color bookmark.textStyle = [PdfTextStyle.bold]; bookmark.color = PdfColor(255, 0, 0); // Save the document List<int> bytes = await document.save(); // Dispose of the document document.dispose(); // Save the file and launch/download SaveFile.saveAndLaunchFile(bytes, 'output.pdf'); }
- Use the following code to save and launch the generated PDF file.
Web:
5.1. Add theweb
package as a dependency in yourpubspec.yaml
file. Then, create a new Dart file namedsave_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;
5.2.To enable file saving and initiate downloads in a Flutter web environment, use the following code within thesaveAndLaunchFile
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:
5.3. Add the following dependencies in your pubspec.yaml file.
path_provider: ^2.0.11 open_file: ^3.2.1 # Open source library to launch the PDF file on mobile devices
5.4. Create a new Dart file named save_file_mobile_and_desktop.dart under the lib folder and import the following packages in the save_file_mobile_and_desktop.dart file.
import 'package:open_file/open_file.dart'; import 'package:path_provider/path_provider.dart'; import 'dart:io';
5.5. Include the following code snippet in save_file_mobile_and_desktop.dart to open the 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 PDF data
File file = File('$path/$fileName');
// Write PDF data
await file.writeAsBytes(bytes, flush: true);
// Open the PDF document on mobile
OpenFile.open('$path/$fileName');
}
}
- Run the sample using the flutter run command. This will add a bookmark to the PDF document page.
After the application launches, you will get the PDF document as follows.
A complete working sample can be downloaded from AddBookmarksToPDF.zip.
Take a moment to peruse the documentation, where you can find other options like adding, Inserting, removing, and modifying bookmarks in an existing PDF document and features like named destination, interactive annotations, and insert hyperlink to PDF with code examples.