Articles in this section
Category / Section

How to create a PDF file in Flutter web platform?

12 mins read

The Syncfusion® Flutter PDF is a non-UI PDF library written natively in Dart for creating PDF documents from scratch. Using this package, you can create a PDF document in Flutter Mobile and Web platforms.

Steps to create a PDF document programmatically in the Web platform:

  1. Create a new Flutter application project.

1.1. Open Visual Studio Code (after installing the Dart and Flutter extensions as stated in the 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 command 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(
                  'Generate PDF',
                  style: TextStyle(color: Colors.white),
                ),
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.resolveWith(
                        (states) => Colors.blue)),
                onPressed: _createPDF,
              )
            ],
          ),
        ),
      );
    }
    

 

  1. Add the following code to the _createPDF function to create a PDF document programmatically.
    Future<void> _createPDF() async {
      // Create a PDF document.
      PdfDocument document = PdfDocument();
      // Add a page and draw text
      document.pages.add().graphics.drawString(
          'Hello World!', PdfStandardFont(PdfFontFamily.helvetica, 20),
          brush: PdfSolidBrush(PdfColor(0, 0, 0)),
          bounds: Rect.fromLTWH(20, 60, 150, 30));
      // Save the document
      List<int> bytes = await document.save();
      // Dispose of the document
      document.dispose();
    }
  1. Use the following code to download the generated PDF file on the web platform.

5.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;

 

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);
}

 

  1. To run the sample on the web platform, follow the steps given in Building a web application with Flutter. Using the flutter run -d chrome command, launch the application in the Chrome browser. This creates a simple PDF document.

 

After the application launches, you will get the application preview and PDF document as follows.

Output image 1 in Flutter PDFOutput image 2 in Flutter PDF

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


Conclusion

I hope you enjoyed learning about how to create a PDF document in Flutter Mobile and Web platforms.



Take a moment to peruse the documentation, where you can find other options like drawing right-to-left text, consuming TrueType fonts, standard fonts, and CJK fonts. Also, explore features like headers and footers, bookmarks, tables, hyperlink PDF documents, and more 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