Blog Post

How to Use Flutter to Create a PDF Document

Illustration: How to Use Flutter to Create a PDF Document

In this post, you’ll learn how to programmatically create PDFs using Flutter.

Flutter is a free, open source framework made by Google that makes it easy to build high-quality, performant mobile iOS and Android apps using a single codebase.

PSPDFKit Flutter PDF Library

PSPDFKit offers a commercial Flutter PDF library that ships with a wide variety of out-of-the-box features, including:

  • A polished and customizable UI that’s easy to integrate into your application.

  • Embeddable prebuilt tools to easily add functionality like annotating documents, adding digital signatures to PDF forms, and much more.

  • Support for multiple file types — from image files (JPG, PNG, TIFF) to PDF documents.

  • Active development cycles with constant improvements and bug fixes.

Requirements

  • A development environment running the Flutter SDK, configured for the platforms you want to build on (iOS, Android, or both)

Getting Started

To create a new Flutter project and integrate PSPDFKit’s library as a dependency, follow our getting started on Flutter guide.

After adding PSPDFKit as a dependency, follow the steps in the next sections.

iOS

  1. Open Runner.xcworkspace from the ios folder in Xcode:

    open ios/Runner.xcworkspace
  2. Make sure the iOS deployment target is set to 14.0 or higher.

Image showing the minimum deployment setting in Xcode

  1. Change View controller-based status bar appearance to YES in your project’s Info.plist.

Image showing the View controller-based status bar appearance setting in Xcode

Android

Modify the base from FlutterActivity to FlutterFragmentActivity, open MainActivity.kt, and add the following:

package com.example.pspdfkit_demo.pspdfkit_demo

-import io.flutter.embedding.android.FlutterActivity
+import io.flutter.embedding.android.FlutterFragmentActivity

-class MainActivity: FlutterActivity() {
+class MainActivity: FlutterFragmentActivity() {
     }

Creating a Blank PDF in Flutter

PSPDFKit’s Flutter library provides the PspdfkitProcessor class, which allows you to generate PDF documents in your application:

var filePath = await PspdfkitProcessor.instance.generatePdf(pages, tempDocumentPath);

You’ll use the generatePdf function in the PspdfkitProcessor class to create a blank PDF document. The generatePdf function expects a list of pages and a path to write the generated document to.

You can create a list of pages you want in a document with the NewPage object. It can define the size of the pages, colors, patterns, images, and pages of other documents:

List<NewPage> pages = [
      // `NewPage` from blank PDF pattern.
      NewPage.fromPattern(PagePattern.blank, pageSize: PageSize.a5),
    ];

To get the path to a temporary directory to which you can write the document, use the getTemporaryDirectory function provided by the Pspdfkit class:

final tempDir = await Pspdfkit.getTemporaryDirectory();
final tempDocumentPath = '${tempDir.path}/blankPdf';

Finally, present the document with the following:

Pspdfkit.present(filePath!);

Putting all the pieces together in the main.dart file, you’ll have this:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:pspdfkit_flutter/pspdfkit.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  void showDocument(BuildContext context) async {
    List<NewPage> pages = [
      // `NewPage` from blank PDF pattern.
      NewPage.fromPattern(PagePattern.blank, pageSize: PageSize.a5),
    ];

    final tempDir = await Pspdfkit.getTemporaryDirectory();
    final tempDocumentPath = '${tempDir.path}/blankPdf';

    var filePath =
        await PspdfkitProcessor.instance.generatePdf(pages, tempDocumentPath);

    await Pspdfkit.present(filePath!);
  }

  @override
  Widget build(BuildContext context) {
    final themeData = Theme.of(context);
    return MaterialApp(
      home: Scaffold(body: Builder(
        builder: (BuildContext context) {
          return Center(
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                ElevatedButton(
                    child: Text('Generate and Open a Blank PDF',
                        style: themeData.textTheme.headline4
                            ?.copyWith(fontSize: 21.0)),
                    onPressed: () => showDocument(context))
              ]));
        },
      )),
    );
  }
}
Information

Copy the code above to your main.dart file in the lib folder for a working example.

Running the Application

  1. Start your iOS simulator or Android emulator, or connect a device.

  2. Run the app with:

    flutter run

iOS

GIF showing the flutter run result with iOS

Android

GIF showing the flutter run result with Android

Conclusion

In this post, you learned how to create and display a blank PDF in Flutter using PSPDFKit. In case of any issues, don’t hesitate to reach out to our Support team for help.

PSPDFKit for Flutter is an SDK for viewing, annotating, and editing PDFs. It offers developers the ability to quickly add PDF functionality to any Flutter application. Try it for free, or visit our demo to see it in action.

Share post
Free trial Ready to get started?
Free trial