Articles in this section
Category / Section

How to create layers in a PDF document using Syncfusion Flutter PDF Library?

8 mins read

The Flutter PDF is a Flutter PDF library used to create, read, and edit PDF documents. Using this library, you can add, update, and remove layers from the PDF document.

Layers, also known as optional content, refer to the sections of content in a PDF document that can be selectively viewed or hidden by document authors or consumers.

Steps to create layers in 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 on the setup editor page).

1.2. Click View -> Command Palette…

Command Palette...

1.3. Type Flutter and choose Flutter: New Project.

Flutter - New Application 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 pub once you trigger the Flutter pub get command or Get packages option from Visual Studio Code.

    dependencies:
      syncfusion_flutter_pdf: ^20.3.49
    

 

  1. 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(
                  'Generate PDF',
                  style: TextStyle(color: Colors.white),
                ),
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.resolveWith(
                        (states) => Colors.blue)),
                onPressed: createLayer,
              )
            ],
          ),
        ),
      );
    }
    

 

  1. Add the following code to the createLayer function to add layers to the PDF document programmatically.
    Future<void> createLayer() async {
      // Create a new PDF document.
      PdfDocument document = PdfDocument();
      // Add a new page to the PDF document.
      PdfPage page = document.pages.add();
      // Add a layer to the PDF page.
      page.layers.add(name: 'Layer 1').graphics.drawString(
          'Layer 1', PdfStandardFont(PdfFontFamily.helvetica, 20),
          bounds: Rect.fromLTWH(100, 60, 100, 50), brush: PdfBrushes.red);
    
      // Add another layer on the page.
      page.layers.add(name: 'Layer 2', visible: false).graphics.drawString(
          'Layer 2', PdfStandardFont(PdfFontFamily.helvetica, 20),
          bounds: Rect.fromLTWH(100, 180, 100, 50), brush: PdfBrushes.green);
    
      // Add another layer.
      page.layers.add(name: 'Layer 3').graphics.drawString(
          'Layer 3', PdfStandardFont(PdfFontFamily.helvetica, 20),
          bounds: Rect.fromLTWH(200, 120, 100, 50), brush: PdfBrushes.blue);
    
      // Save and dispose of the document.
      final List<int> bytes = await document.save();
      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:

       

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

c. Add the following dependencies in your pubspec.yaml file.

open_file: ^3.2.1 # Open-source library to launch the PDF file in mobile devices
path_provider: ^2.0.11

 

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

 

e. 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');
  }
}
  1. Run the sample using the flutter run command. This will create layers in the PDF document. After the application launches, you will get the PDF document as follows.

PDF Conformance

A complete working sample can be downloaded from layers.zip.


Conclusion:

I hope you enjoyed learning about how to create layers in a PDF document using Syncfusion® Flutter PDF Library.

Take a moment to peruse the documentation. You can find other options like adding layerstoggling the visibility of layers, removing layers from an existing PDF document, nesting layer, and flattening the layers in an existing document.

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