How to print/save the flutter application screen as pdf?

Hey flutter folks.!

Ever wondered how can we export a flutter application screen as a pdf? Let's get started.

First of all, we need to add two packages to our pubspec.yaml file.

pdf: ^3.6.5

printing: ^5.6.6

They provide android, ios as well as web support.

This is the simple screen layout that we will use to demo the function

import 'package:flutter/material.dart';class ScreenToPdf extends StatelessWidget {@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text('Screen to PDF'),),body: Center(child: Column(mainAxisAlignment:,children: ['',height: 200,width: 200,),const SizedBox(height: 20,),ElevatedButton(child: const Text('Screen to PDF'),onPressed: () {},),const Text('Printing the data from the screen to PDF'),],),),);}}
This is the basic layout

Import the necessary dart files:

import ‘package:pdf/pdf.dart’;

import ‘package:pdf/widgets.dart ‘ as pw;

import ‘package:printing/printing.dart’;

Now declare a global key as shown below:

final GlobalKey<State<StatefulWidget>> _printKey = GlobalKey();

Wrap the widget tree with the Repaint Boundary and pass the key as the parameter:

Widget build(BuildContext context) {
return RepaintBoundary(
key: _printKey,
child: Scaffold(...)

_printScreen() is the function that will export the screen as pdf and we can either print it or save it as a pdf. Here pass your global key as a parameter and call the _printScreen() in the elevated button’s onPressed method.

void _printScreen() async {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),),);}));

Video showing the usage of the application

This is how the saved pdf looks:

Downloaded pdf


  • This method will not work if any media component such as Youtube Player, Video player, etc are present in the widget tree as they can’t be rendered in a pdf. Make sure you are wrapping only the widget tree where any media component is not present.

Source code for this project:

If you like it then please support me by clapping and following me on medium. Thank you for reading!

You can also connect with me on Linkedin or can email me.