Skip to main content
Skip table of contents

How to use iText with Flutter?

Overview

This guide demonstrates how to integrate iText into a Flutter application to natively generate PDFs on mobile devices.

👉 We will make use of Flutters MethodChannel class to bridge the code between Flutter, and the native Android code (Java) where iText runs.
👉 For iOS, you would need a back-end service to generate the PDFs (iText cannot run natively on iOS)

Prerequisites:

  • Flutter SDK (all checks in flutter doctor should pass)

  • IntelliJ or Android Studio

  • Android device/emulator for testing (Android Device Manager)

  • A valid iText license

  • XCode (iOS Simulator) - For iOS

This is a simple Flutter application with a simple button that demonstrates the use of the iText API within a mobile application built with Flutter SDK.

Structure

  • lib/main.dart : Flutter UI Page with a “Generate PDF” button.

  • Native integration via MethodChannel to call Android code (this example provides Java integration, you may use Kotlin)

  • MainActivity.Java (PDF logic with iText)

  • A valid iText license

Step-by-Step Setup

  1. lib/main.dart: The Dart code below defines a Button in Flutter UI that calls native Android methods to generate a PDF in the device’s local file system:

    DART
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      static const platform = MethodChannel('flutter_pdf');
    
      Future<void> _generatePdf() async {
        try {
          final path = await platform.invokeMethod<String>('generatePdf');
          print('PDF created at: $path');
          _showDialog(path!);
        } catch (e) {
          print('Error: $e');
        }
      }
    
      void _showDialog(String path) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          showDialog(
            context: navigatorKey.currentContext!,
            builder: (_) => AlertDialog(
              title: Text("PDF Generated"),
              content: Text("Saved at:\n$path"),
              actions: [
                TextButton(child: Text("OK"), onPressed: () => Navigator.pop(navigatorKey.currentContext!))
              ],
            ),
          );
        });
      }
    
      static final navigatorKey = GlobalKey<NavigatorState>();
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          navigatorKey: navigatorKey,
          home: Scaffold(
            appBar: AppBar(title: Text("Flutter iText integration")),
            body: Center(
              child: ElevatedButton(
                onPressed: _generatePdf,
                child: Text("Generate PDF"),
              ),
            ),
          ),
        );
      }
    }
  2. Adding iText dependencies & depository config
    👉 We need to first configure the iText dependencies, before we can move to Step 3 to write some code to perform iText operations.
    To add repository link:
    Path: android/build.gradle and then add:

    CODE
    allprojects {
        repositories {
            google()
            mavenCentral()
           maven {
               url = uri("https://repo.itextsupport.com/releases")
           }
        }
    }

    To add dependencies:
    Path: android/app/build.gradle and then add:

    CODE
    dependencies {
        implementation ("com.itextpdf:itext-core:9.2.0")
    }

For this project I am using Kotlin DSL but you may use Groovy as well.

  1. Native Android code so our Flutter UI can communicate via MethodChannel to perform iText operations.
    Path : android/app/src/main/java/com/example/itextdemo/MainActivity.Java

    JAVA
    import android.os.Bundle;
    import io.flutter.embedding.android.FlutterActivity;
    import io.flutter.plugin.common.MethodChannel;
    
    import java.io.File;
    import java.io.FileOutputStream;
    
    import com.itextpdf.kernel.pdf.PdfWriter;
    import com.itextpdf.kernel.pdf.PdfDocument;
    import com.itextpdf.layout.Document;
    import com.itextpdf.layout.element.Paragraph;
    
    public class MainActivity extends FlutterActivity {
        private static final String CHANNEL = "flutter_pdf";
    
        @Override
        public void configureFlutterEngine(io.flutter.embedding.engine.FlutterEngine flutterEngine) {
            super.configureFlutterEngine(flutterEngine);
    
            new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                    .setMethodCallHandler((call, result) -> {
                        if (call.method.equals("generatePdf")) {
                            try {
                                File file = new File(getCacheDir(), "sample_01.pdf");
                                PdfWriter writer = new PdfWriter(new FileOutputStream(file));
                                PdfDocument pdf = new PdfDocument(writer);
                                Document doc = new Document(pdf);
                                doc.add(new Paragraph("Hello from iText and Flutter!"));
                                doc.close();
                                result.success(file.getAbsolutePath());
                            } catch (Exception e) {
                                result.error("PDF_ERROR", e.getMessage(), null);
                            }
                        }
                    });
        }
    }
  2. Run the application & test the PDF generation
    👉 Run flutter pub get in your IDE console
    👉 Start an Android emulator or connect a device
    👉 Run flutter run in your IDE console to start the app
    👉 Tap the Generate PDF Button in the UI → A sample PDF file will be saved to your device’s storage

fluttersdk.png

The sample generated PDF from our application

Resources

➡️ iTextdemo.zip - Zip folder with a working basic Flutter & iText integration

➡️ sample_01.pdf- A sample generated PDF

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.