Converting Flutter Screens to Shareable PDFs: A Complete Guide

Sep 25, 2024

Converting Flutter Screens to Shareable PDFs: A Complete Guide

Learn how to convert a Flutter screen or widget into a shareable PDF and seamlessly share it with other apps in just a few steps.

Author

Priyanka Singla
Priyanka SinglaSoftware Engineer - II

Sharing PDFs is a crucial feature for many modern mobile applications. Whether you're generating invoices, reports, or any other documents, enabling PDF generation and sharing is a vital part of creating interactive and feature-rich applications.

In this guide, we'll walk through how to integrate PDF generation and sharing functionality in your Flutter app using the pdf, path_provider, and share_plus packages. By the end of this article, you can generate, display, and share a PDF file right from your Flutter application.

Why PDFs?

PDFs are universally accepted and accessible on any device, making them an ideal format for documents like receipts, reports, or contracts. Integrating PDF generation into your Flutter app allows you to deliver this functionality directly to your users, keeping them engaged and providing a convenient way to export information from your app.

Key Features of PDF Generation and Sharing

  • Cross-Platform Support: Just like OneSignal, the libraries weโ€™ll use support both Android and iOS, enabling you to use a single solution for both platforms.
  • Simple Integration: Using the pdf and share_plus packages, Flutter developers can easily implement PDF generation and sharing functionality with minimal code.
  • Rich PDF Content: Create PDFs that contain rich content like text, tables, and even images, making your application more interactive and engaging.

Steps to Implement PDF Generation and Sharing in Flutter

1. Install the Required Plugins

To get started, you need to add the necessary dependencies to your pubspec.yaml file. These plugins provide the foundation for PDF creation, accessing the file system, and sharing the generated files.

 dependencies:
  flutter:
    sdk: flutter
  pdf: ^3.11.1
  path_provider: ^2.1.4
  share_plus: ^10.0.2
  • pdf: This package provides tools for creating PDF files.
  • path_provider: This plugin allows us to access directories on the device's file system.
  • share_plus: This package enables the sharing of files with other apps, making it easy to send PDFs.

After adding the dependencies, run flutter pub get to install them.


2. Basic Setup for PDF Generation and Sharing

In this step, weโ€™ll write a Flutter function to generate a basic PDF document containing some sample content, followed by sharing the generated PDF using the share_plus plugin.

Step 1: Generating a PDF

First, let's write the method to generate a simple PDF. In this example, we'll create a PDF with text content such as an invoice or receipt.

import 'package:pdf/widgets.dart' as pw;
import 'package:path_provider/path_provider.dart';
import 'dart:io';

Future<void> generatePdf() async {
  final pdf = pw.Document();

  // Add content to the PDF
  pdf.addPage(
    pw.Page(
      build: (pw.Context context) => pw.Center(
        child: pw.Text("Hello, this is a sample PDF!"),
      ),
    ),
  );

  // Get the temporary directory of the device
  final directory = await getTemporaryDirectory();
  final file = File("${directory.path}/sample.pdf");

  // Write the PDF to the file
  await file.writeAsBytes(await pdf.save());
}

Hereโ€™s whatโ€™s happening:

  • PDF Creation: We use the pdf package to create a document (pw.Document()) and add content (text, in this case) to it.
  • File Storage: The generated PDF is stored in the temporary directory of the device using the path_provider plugin.

Step 2: Sharing the PDF

Once the PDF is generated, you can use the share_plus plugin to share the file with other applications, such as email or messaging apps. Hereโ€™s how to implement the sharing functionality:

import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';

Future<void> sharePdf() async {
  final directory = await getTemporaryDirectory();
  final file = File("${directory.path}/sample.pdf");

  // Share the PDF file
  await Share.shareXFiles([XFile(file.path)], text: 'Here is a sample PDF!');
}

In this method, the file is retrieved from the temporary directory, and the shareXFiles method of the share_plus plugin is used to share it.

3. Complete Integration: Generate and Share PDFs

With both PDF generation and sharing functions in place, letโ€™s integrate everything into a simple Flutter application. Below is the complete code that handles generating and sharing a sample PDF:

Complete Code Example

main.dart

import 'package:build_pdf/bill_page.dart';
import 'package:flutter/material.dart';

void main() {
 runApp(const MyApp());
}

class MyApp extends StatelessWidget {
 const MyApp({super.key});


 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     title: 'Bill Review',
     debugShowCheckedModeBanner: false,
     theme: ThemeData(
       primarySwatch: Colors.blue,
     ),
     home: BillPage(),
   );
 }
}

bill_page.dart

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'dart:io';

class BillPage extends StatelessWidget {
  BillPage({super.key});

  // Sample bill data
  final String orderId = '12345';
  final DateTime now = DateTime.now();
  final List<Map<String, dynamic>> items = [
    {'description': 'Item 1', 'quantity': 2, 'price': 50.0},
    {'description': 'Item 2', 'quantity': 1, 'price': 100.0},
  ];
  final double tax = 8.8;

  @override
  Widget build(BuildContext context) {
    // Calculate total amount
    double totalAmount = items.fold(0.0,
            (double sum, item) => sum + (item['quantity'] * item['price'])) *
        (1 + tax / 100);

    return Scaffold(
      appBar: AppBar(
        title: const Text('Generate Simple Bill'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              "INVOICE",
              style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            Text("Order ID: $orderId"),
            Text("Date: ${DateFormat('MM-dd-yyyy').format(now)}"),
            const SizedBox(height: 16),
            const Text('Bill Details', style: TextStyle(fontSize: 16)),
            const SizedBox(height: 8),
            Table(
              border: TableBorder.all(color: Colors.black, width: 1.0),
              children: [
                const TableRow(children: [
                  Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text('Description'),
                  ),
                  Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text('Quantity'),
                  ),
                  Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text('Price'),
                  ),
                ]),
                ...items.map((item) {
                  return TableRow(children: [
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(item['description']),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(item['quantity'].toString()),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text('\$${item['price'].toStringAsFixed(2)}'),
                    ),
                  ]);
                }),
                TableRow(children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text('Tax @ $tax%'),
                  ),
                  const Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text(''),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                        '\$${(totalAmount - (totalAmount / (1 + tax / 100))).toStringAsFixed(2)}'),
                  ),
                ]),
                TableRow(children: [
                  const Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text('Total'),
                  ),
                  const Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text(''),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text('\$${totalAmount.toStringAsFixed(2)}'),
                  ),
                ]),
              ],
            ),
            const SizedBox(height: 20),
            Center(
              child: ElevatedButton(
                onPressed: () => generateBillPdf(context),
                child: const Text('Generate and Share PDF'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Generate the PDF and share it
  Future<void> generateBillPdf(BuildContext context) async {
    final pdf = pw.Document();

    // Calculate total amount
    double totalAmount = items.fold(0.0,
            (double sum, item) => sum + (item['quantity'] * item['price'])) *
        (1 + tax / 100);

    // Add content to the PDF
    pdf.addPage(
      pw.Page(
        build: (pw.Context context) => pw.Column(
          crossAxisAlignment: pw.CrossAxisAlignment.start,
          children: [
            pw.Text(
              "INVOICE",
              style: pw.TextStyle(
                fontSize: 25,
                fontWeight: pw.FontWeight.bold,
              ),
            ),
            pw.SizedBox(height: 16),
            pw.Text("Order ID: $orderId"),
            pw.Text("Date: ${DateFormat('MM-dd-yyyy').format(now)}"),
            pw.SizedBox(height: 16),
            pw.Text('Bill Details', style: const pw.TextStyle(fontSize: 16)),
            pw.SizedBox(height: 8),
            pw.Table(
              border: pw.TableBorder.all(color: PdfColors.black, width: 1.0),
              children: [
                pw.TableRow(children: [
                  pw.Padding(
                    padding: const pw.EdgeInsets.all(8.0),
                    child: pw.Text('Description'),
                  ),
                  pw.Padding(
                    padding: const pw.EdgeInsets.all(8.0),
                    child: pw.Text('Quantity'),
                  ),
                  pw.Padding(
                    padding: const pw.EdgeInsets.all(8.0),
                    child: pw.Text('Price'),
                  ),
                ]),
                ...items.map((item) {
                  return pw.TableRow(children: [
                    pw.Padding(
                      padding: const pw.EdgeInsets.all(8.0),
                      child: pw.Text(item['description']),
                    ),
                    pw.Padding(
                      padding: const pw.EdgeInsets.all(8.0),
                      child: pw.Text(item['quantity'].toString()),
                    ),
                    pw.Padding(
                      padding: const pw.EdgeInsets.all(8.0),
                      child: pw.Text('\$${item['price'].toStringAsFixed(2)}'),
                    ),
                  ]);
                }),
                pw.TableRow(children: [
                  pw.Padding(
                    padding: const pw.EdgeInsets.all(8.0),
                    child: pw.Text('Tax @ $tax%'),
                  ),
                  pw.Padding(
                    padding: const pw.EdgeInsets.all(8.0),
                    child: pw.Text(''),
                  ),
                  pw.Padding(
                    padding: const pw.EdgeInsets.all(8.0),
                    child: pw.Text(
                        '\$${(totalAmount - (totalAmount / (1 + tax / 100))).toStringAsFixed(2)}'),
                  ),
                ]),
                pw.TableRow(children: [
                  pw.Padding(
                    padding: const pw.EdgeInsets.all(8.0),
                    child: pw.Text('Total'),
                  ),
                  pw.Padding(
                    padding: const pw.EdgeInsets.all(8.0),
                    child: pw.Text(''),
                  ),
                  pw.Padding(
                    padding: const pw.EdgeInsets.all(8.0),
                    child: pw.Text('\$${totalAmount.toStringAsFixed(2)}'),
                  ),
                ]),
              ],
            ),
          ],
        ),
      ),
    );

    // Get the temporary directory
    final output = await getTemporaryDirectory();

    // Create the file name
    final file = File("${output.path}/SimpleBill.pdf");

    // Write the PDF to the file
    await file.writeAsBytes(await pdf.save());

    // Share the PDF file
    await Share.shareXFiles([XFile(file.path)]);
  }
}
  • PDF Generation: When the button is pressed, the app generates a PDF with sample content and saves it to the temporary directory.

PDF Sharing: Once the PDF is saved, the app allows users to share it with other apps (email, messaging, etc.) using the deviceโ€™s native share sheet.

For a hands-on experience and to better understand the workflow, dive into the code. Feel free to explore the implementation via this GitHub repository.

Conclusion

Incorporating PDF generation and sharing into your Flutter application adds a valuable feature, allowing users to export and share documents seamlessly. With just a few lines of code, you can provide this functionality across both iOS and Android, improving the user experience and adding professional document handling to your app.

By using the pdf, path_provider, and share_plus packages, you can easily implement this functionality and offer a complete solution for PDF generation and sharing in your Flutter projects.

Subscribe to Our Newsletter

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
Insight
Building a Production-Ready Canva-like Editor with Konva.js, React 19 and Next.js 15
Sep 10, 2026

Building a Production-Ready Canva-like Editor with Konva.js, React 19 and Next.js 15

This blog explains how to build a production-ready canvas editor with Konva.js, React, and Next.js, covering architecture, performance, and key engineering decisions.

Insight
What a PHP-to-NestJS Banking Migration Taught Us About Architecture, Security, and Trust
Sep 8, 2026

What a PHP-to-NestJS Banking Migration Taught Us About Architecture, Security, and Trust

This blog explores the architecture, security, performance, and documentation lessons from migrating a legacy PHP/Laravel banking platform to NestJS.

Insight
Building Production-Grade Video Thumbnail Scrubbing in the Browser: HLS, Frame Extraction, Caching, and Performance Trade-offs
Sep 7, 2026

Building Production-Grade Video Thumbnail Scrubbing in the Browser: HLS, Frame Extraction, Caching, and Performance Trade-offs

This blog explains how to build responsive video thumbnail scrubbing in the browser for local files and HLS streams, covering frame extraction, caching, and performance trade-offs.

Insight
The Agent Can See Your App. How Often Can It Look?
Sep 4, 2026

The Agent Can See Your App. How Often Can It Look?

AI coding agents can now interact with mobile apps, but their effectiveness depends on iteration speed. This blog explores how React Native architecture influences feedback loops and AI-driven developer productivity.

Insight
Building Interactive Cards from Design JSON Without Killing Your Feed: Overlays, Video, Mute/Unmute, and Lag-Free Lists
Sep 1, 2026

Building Interactive Cards from Design JSON Without Killing Your Feed: Overlays, Video, Mute/Unmute, and Lag-Free Lists

Learn how to turn design JSON into interactive, video-enabled cards using overlays, smart media controls, caching, and virtualization without slowing down high-cardinality feeds.

Insight
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
Aug 19, 2026

The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari

A real-world look at how oversized images can trigger Safari reloads and iOS crashes in Flutter apps and how smarter image decoding prevents them.

Insight
From Prompting to Process: What Changed When Flutter Shipped Agent Skills
Aug 19, 2026

From Prompting to Process: What Changed When Flutter Shipped Agent Skills

This blog explores how Flutter Agent Skills improve AI-assisted development by combining official framework workflows with project-specific guidance for more consistent development.

The Right Conversation Can

Save You Six Months.

Book a call