Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export Flutter application screen to PDF

Tags:

is there any possible way to export flutter app screen/s to PDF, what im looking for is similar to screenshot function, but it should generate PDF rather than a picture.

Thanks in advance

like image 756
Sohaib Al Abbadi Avatar asked May 02 '20 17:05

Sohaib Al Abbadi


People also ask

How do you create a PDF on flutter Web?

Using the flutter run -d chrome command, launch the application in chrome browser. This creates a simple PDF document.

How do I convert a widget to an image in flutter?

Inside our RepaintBoundary, we will pass the widget that needs to be converted to image. after that we create a function called capturePng which will resolve a future of type Future<Uint8List>. Inside it, we create a RenderRepaintBoundary object and assign it RenderObject via currentContext.


1 Answers

You can use pdf/printing this way:

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:printing/printing.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  final GlobalKey<State<StatefulWidget>> _printKey = GlobalKey();

  void _printScreen() {
    Printing.layoutPdf(onLayout: (PdfPageFormat format) async {
      final doc = pw.Document();

      final image = await WidgetWraper.fromKey(
        key: _printKey,
        pixelRatio: 2.0,
      );

      doc.addPage(pw.Page(
          pageFormat: format,
          build: (pw.Context context) {
            return pw.Center(
              child: pw.Expanded(
                child: pw.Image(image),
              ),
            );
          }));

      return doc.save();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            RepaintBoundary(
              key: _printKey,
              child:
                  // This is the widget that will be printed.
                  const FlutterLogo(
                size: 300,
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.print),
        onPressed: _printScreen,
      ),
    );
  }
}
like image 87
Dav Avatar answered Oct 03 '22 13:10

Dav