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.

Nutrient Flutter PDF library

We offer a commercial Flutter PDF library with detailed getting started guides. Our Nutrient 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 Nutrient’s library as a dependency, follow our getting started on Flutter guide.

After adding Nutrient 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

Nutrient’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 Nutrient. If you have any issues, don’t hesitate to reach out to our Support team for help.

The Nutrient 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.

FAQ

Here are a few frequently asked questions about image conversion in Flutter.

How do I handle large images when converting them to PDF in Flutter?

To manage large images, consider resizing or compressing them using Dart packages before conversion to ensure the final PDF size is manageable.

Is this PDF generation solution compatible with both iOS and Android?

Yes, Nutrient supports cross-platform development, so the solution works seamlessly on both iOS and Android devices.

Can I modify the page size and layout of the generated PDF?

Absolutely. You can customize the page size, orientation, and other properties using the NewPage class in Nutrient.

What happens if the user cancels image selection in the app?

If the user cancels the file picker, you can handle this by checking if the result is null and showing a fallback message or action.

Do I need to install any additional packages to pick image files?

Yes, you’ll need to add the file_picker package to your Flutter project for selecting images from the device.

Explore related topics

Share post
Free trial Ready to get started?
Free trial