DARIO
DARIO

Reputation: 35

Flutter: How to export a screen as a PDF

I am trying to export the following screen:

enter image description here

as a PDF or Doc in Flutter.

So, the user will be able to enter some data in TextFields and when they finish they can download the whole page as a doc or PDF Document.

I am new so any suggestion will be greate.

Thank you Guys

Upvotes: 2

Views: 5895

Answers (3)

Alamgir Khan
Alamgir Khan

Reputation: 135

For someone who wants the same to take screenshots and then export in this example taking screenshots from widgets but in the package docs you can read how to take screenshots from the entire screen which is way easy.

Packages used: https://pub.dev/packages/pdf https://pub.dev/packages/screenshot

import 'dart:io';
import 'dart:math';

import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

class HomeScreen extends StatefulWidget {
  static const String routeName = '/home';

  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final ScreenshotController _screenshotController = ScreenshotController();
  
  @override
  Widget build(BuildContext context) {
    return return SafeArea(
      child: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        controller: _scrollController,
        child: RepaintBoundary(
          key: _globalKey,
          child: Padding(
            padding: const EdgeInsets.symmetric(
              horizontal: 15.0,
              vertical: 0.0,
            ),
            child: Center(
              child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blueAccent,
                      padding: const EdgeInsets.all(0),
                    ),
                    onPressed: () {
                      _takeScreenshot(context, state);
                    },
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: const [
                        Icon(
                          Icons.picture_as_pdf,
                          size: 15,
                        ),
                      ],
                    ),
                  ),
            ),
          ),
        ),
      ),
    );
  }

  // the widget that need to be the one we want to take screenshot
  _someWidget() {
    return Text('Hope it will help you');
  }

  String _getRandomString(int length) {
    const chars =
        'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
    Random rnd = Random();
    return String.fromCharCodes(Iterable.generate(
        length, (_) => chars.codeUnitAt(rnd.nextInt(chars.length))));
  }
  
  // Take a screenshot
  _takeScreenshot(BuildContext context, OrderState state) {
    Widget container = _someWidget();
    _screenshotController
        .captureFromWidget(
            InheritedTheme.captureAll(context, Material(child: container)),
            delay: const Duration(seconds: 1))
        .then((capturedImage) {
      _exportScreenshotToPdf(context, capturedImage);
    });
  }

  // Export the screenshot as pdf
  Future<dynamic> _exportScreenshotToPdf(
      BuildContext context, Uint8List screenShot) async {
    pw.Document pdf = pw.Document();
    pdf.addPage(
      pw.Page(
        pageFormat: PdfPageFormat.a4,
        build: (context) {
          return pw.Expanded(
            child: pw.Image(pw.MemoryImage(screenShot), fit: pw.BoxFit.contain),
          );
        },
      ),
    );
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String documentPath = documentDirectory.path;

    File pdfFile = File(
        '$documentPath/${'${_getRandomString(10)}-${formatDate(DateTime.now(), [
          dd,
          '-',
          mm,
          '-',
          yyyy
        ])}'}.pdf');
    pdfFile.writeAsBytesSync(await pdf.save());
  }

Upvotes: 2

Moaz El-sawaf
Moaz El-sawaf

Reputation: 3059

Welcome to Flutter 💙

There are a large set of packages that can deal with PDF in Flutter, wheter to create them such as in your case, or to preview them.

You can check this gallery of package from fluttergemes.dev to access a large set of PDF pacakges with Flutter.

Also you can find a large number of videos in YouTube that explains how to create a PDF with Flutter.

Upvotes: 1

Ra&#250;l Fuentes
Ra&#250;l Fuentes

Reputation: 46

What you are looking for is this, it is a library for creating a PDF with Widgets.

Upvotes: 0

Related Questions