Blog Post

How to Convert an Image to a PDF in Flutter

Illustration: How to Convert an Image to a PDF in Flutter

In this post, you’ll learn how to convert an image to a PDF using Flutter.

Flutter is a free, open source framework made by Google that makes it easy to build iOS and Android apps using a single codebase in Dart.

PSPDFKit Flutter PDF Library

We offer a commercial Flutter PDF library with detailed getting started guides. Our PSPDFKit Flutter PDF library ships with many features out of the box, including:

Requirements

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

Dependencies

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

  3. 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() {
     }

The file_picker Package

  1. Add the file_picker dependency in pubspec.yaml:

    dependencies:
    flutter:
        sdk: flutter
    + file_picker: ^5.2.2
  2. From the terminal app, run the following command to get all the packages:

    flutter packages get
  3. Then run the command below to upgrade the dependencies:

    flutter packages get upgrade

Converting an Image to a PDF Document

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 PDF document from an image file. 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 page, colors, patterns, images, and pages of other documents:

var pages = [
        NewPage.fromImage(PdfImagePage.fromUri(img.uri, PagePosition.center),
            pageSize: PageSize.a0),
        NewPage.fromImage(PdfImagePage.fromUri(img.uri, PagePosition.bottom),
            pageSize: PageSize.a0),
        NewPage.fromImage(PdfImagePage.fromUri(img.uri, PagePosition.top),
            pageSize: PageSize.a0)
      ];

Use the file_picker package in your dependencies to get a uri⁣ to the user’s choice image:

FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
      File img = File(result.files.single.path!);

    } else {
      // User canceled the picker.
    }
  }

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, you can 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';
import 'package:file_picker/file_picker.dart';

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

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

class _MyAppState extends State<MyApp> {
  void showDocument(BuildContext context) async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
      File img = File(result.files.single.path!);

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

      var pages = [
        NewPage.fromImage(PdfImagePage.fromUri(img.uri, PagePosition.center),
            pageSize: PageSize.a0),
        NewPage.fromImage(PdfImagePage.fromUri(img.uri, PagePosition.bottom),
            pageSize: PageSize.a0),
        NewPage.fromImage(PdfImagePage.fromUri(img.uri, PagePosition.top),
            pageSize: PageSize.a0)
      ];

      var filePath =
          await PspdfkitProcessor.instance.generatePdf(pages, tempDocumentPath);
      await Pspdfkit.present(filePath!);
    } else {
      // User canceled the picker.
    }
  }

  @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('Select an Image File',
                        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 convert an image to a PDF in Flutter using PSPDFKit. If you have any issues, don’t hesitate to reach out to our Support team for help.

The PSPDFKit PDF library for Flutter allows 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 60-Day Trial Try PSPDFKit in your app today.
Free Trial

Related Articles

Explore more
PRODUCTS  |  Flutter • Releases

PSPDFKit 3.9 for Flutter with Toolbar Customization

PRODUCTS  |  Flutter • Releases

PSPDFKit 3.8 for Flutter with Web Support

PRODUCTS  |  Flutter • Releases

PSPDFKit 3.7 for Flutter Adds Annotation Preset Customization