Articles in this section
Category / Section

How to add bookmarks in a PDF using Syncfusion Flutter PDF Library?

3 mins read

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

  1. 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…

Command Palette...

1.3.Type Flutter and choose Flutter: New Project.

Flutter - New Project

1.4.Enter the project name and press the Enter button.

1.5.Now choose the location of the project.

  1. 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';

 

  1. 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,
              )
            ],
          ),
        ),
      );
    }
    

 

  1. 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();
      //Adds a page
      PdfPage page = document.pages.add();
      //Creates a bookmark
      PdfBookmark bookmark = document.bookmarks.add('Chapter 1');
      //Sets the destination page and locaiton
      bookmark.destination = PdfDestination(page, Offset(10, 10));
      //Draw the content in the PDF page
      page.graphics.drawString(
          'Chapter1', PdfStandardFont(PdfFontFamily.helvetica, 10),
          brush: PdfBrushes.red, bounds: Rect.fromLTWH(10, 10, 0, 0));
      //Adds the child bookmark
      PdfBookmark childBookmark = bookmark.insert(0, 'Section 1');
      childBookmark.destination = PdfDestination(page, Offset(30, 30));
      //Draw the content in the PDF page
      page.graphics.drawString(
          'Section1', PdfStandardFont(PdfFontFamily.helvetica, 10),
          brush: PdfBrushes.green, bounds: Rect.fromLTWH(30, 30, 0, 0));
      //Sets 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 the document.
      document.dispose();
      //Save the file and launch/download.
      SaveFile.saveAndLaunchFile(bytes, 'output.pdf');
     
    }
    

 

  1. Use the following code to save and launch the generated PDF file.

       Web:

5.1.Create a new dart file named save_file_web.dart under the lib folder and import the following packages in save_file_web.dart file.

import 'dart:convert';
import 'dart:html';

5.2.Include the following code snippet in save_file_web.dart file to open the PDF document in Web.

class SaveFile {
  static Future<void> saveAndLaunchFile(
      List<int> bytes, String fileName) async {
    AnchorElement(
        href:
            'data:application/octet-stream;charset=utf-16le;base64,${base64.encode(bytes)}')
      ..setAttribute('download', fileName)
      ..click();
  }
}

       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 in 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 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 in 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 in mobile
    OpenFile.open('$path/$fileName');
  }
}
  1. Run the sample using the flutter run command. This will add bookmark to the PDF document page.
    After the application launches, you will get the PDF document as follows.

Output Pdf document 1 in Flutter PDF   Output Pdf document 2 in Flutter PDF

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.

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied