In this tutorial we are going to make a pdf using the flutter pdf library. Working with PDF in Flutter is the common requirement into the business app, e-commerce app, utility app and more etc. This library allow you to generate the digital pdf into the correct way so let’s wrap the things and continue to looking below for the full tutorial.
This tutorial will cover:
- What is pdf in flutter?
- What are the best pdf generator libraries in flutter?
- How to generate pdf in pdf?
- How to save generated pdf in flutter?
What is a PDF?
Flutter PDF refers to creating, reading, exporting or sharing text, images tables document directly inside a flutter application. With the help of packages like pdf or printing we can easily do:
- Create pdf
- View pdf
- Share pdf
- save pdf
Flutter allow both Android and IOS smooth pdf working.
What are the Best Pdf Generating Libraries in Flutter?
There some some libraries into Flutter to generate, view or export the pdf smoothly, those are as below:
1.pdf (free | most popular)
- This is free pdf making library.
- Mostly used library.
- Supports, text, tables, images, layout and fonts, for more click here.
2.printing
- Used for Pdf preview
- Its totally free to use
- It allows Print, Share and Download Option.
- You can integrate perfectly with the pdf package easily.
3.flutter_pdfview
- Its free also to view the pdf documents.
- You can view the PDF document with the help of this package.
4.syncfusion_flutter_pdf
- This is paid enterprises level package.
- Advanced features like pdf editing and annotation.
How to Generate and Save a PDF into Flutter?
Let’s focus into the below steps to generate and save the pdf:
1. Step 1: Add Depedencies
Add the following dependencies into the pubspec.yml file :
dependencies:
pdf: ^3.10.4
printing: ^5.12.0
or
You can run this command into the terminal:
: flutter pub add printing pdf
Then run this command to sync the dependencies:
: flutter pub get
2.Step 2: Create a simple Pdf file
Using the pdf package create a simple widget file:
import 'dart:io';
import 'package:pdf/widgets.dart' as pw;
Future<void> main() async {
final pdf = pw.Document();
pdf.addPage(
pw.Page(
build: (pw.Context context) => pw.Center(
child: pw.Text('Hello World!'),
),
),
);
final file = File('example.pdf');
await file.writeAsBytes(await pdf.save());
}
To load an image from mobile use this:
final image = pw.MemoryImage(
File('test.webp').readAsBytesSync(),
);
pdf.addPage(pw.Page(build: (pw.Context context) {
return pw.Center(
child: pw.Image(image),
); // Center
})); // Page
To load an image from asset file (web):
Create a Uint8List from the image
final img = await rootBundle.load('assets/images/logo.jpg');
final imageBytes = img.buffer.asUint8List();
Create an image from the ImageBytes
pw.Image image1 = pw.Image(pw.MemoryImage(imageBytes));
implement the image in a container
pw.Container(
alignment: pw.Alignment.center,
height: 200,
child: image1,
);
To load an image from the network using the printing package:
final netImage = await networkImage('https://www.nfet.net/nfet.jpg');
pdf.addPage(pw.Page(build: (pw.Context context) {
return pw.Center(
child: pw.Image(netImage),
); // Center
})); // Page
To load an SVG:
String svgRaw = '''
<svg viewBox="0 0 50 50" xmlns="http://www.w3.org/2000/svg">
<ellipse style="fill: grey; stroke: black;" cx="25" cy="25" rx="20" ry="20"></ellipse>
</svg>
''';
final svgImage = pw.SvgImage(svg: svgRaw);
pdf.addPage(pw.Page(build: (pw.Context context) {
return pw.Center(
child: svgImage,
); // Center
})); // Page
To load the SVG from a Flutter asset, use await rootBundle.loadString('assets/file.svg')
To use a TrueType font:
final Uint8List fontData = File('open-sans.ttf').readAsBytesSync();
final ttf = pw.Font.ttf(fontData.buffer.asByteData());
pdf.addPage(pw.Page(
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
return pw.Center(
child: pw.Text('Hello World', style: pw.TextStyle(font: ttf, fontSize: 40)),
); // Center
})); // Page
Or using the printing package’s PdfGoogleFonts:
final font = await PdfGoogleFonts.nunitoExtraLight();
pdf.addPage(pw.Page(
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
return pw.Center(
child: pw.Text('Hello World', style: pw.TextStyle(font: font, fontSize: 40)),
); // Center
})); // Page
To display emojis:
final emoji = await PdfGoogleFonts.notoColorEmoji();
pdf.addPage(pw.Page(
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
return pw.Center(
child: pw.Text(
'Hello 🐒💁👌🎍😍🦊👨 world!',
style: pw.TextStyle(
fontFallback: [emoji],
fontSize: 25,
),
),
); // Center
})); // Page
3.Saving the PDF
// On Flutter, use the [path_provider](https://pub.dev/packages/path_provider) library:
// final output = await getTemporaryDirectory();
// final file = File("${output.path}/example.pdf");
final file = File("example.pdf");
await file.writeAsBytes(await pdf.save());
To save the pdf file (Web): (saved as a unique name based on milliseconds since epoch)
var savedFile = await pdf.save();
List<int> fileInts = List.from(savedFile);
web.HTMLAnchorElement()
..href = "data:application/octet-stream;charset=utf-16le;base64,${base64.encode(fileInts)}"
..setAttribute("download", "${DateTime.now().millisecondsSinceEpoch}.pdf")
..click();
Previewing PDF using printing
Add these libraries while creating the file widget:
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:printing/printing.dart';
For more ios and android setting plaase click here.
See all the examples:
To load an image from a Flutter asset:
final image = await imageFromAssetBundle('assets/image.png');
doc.addPage(pw.Page(
build: (pw.Context context) {
return pw.Center(
child: pw.Image(image),
); // Center
})); // Page
To use a TrueType font from a flutter bundle:
final ttf = await fontFromAssetBundle('assets/open-sans.ttf');
doc.addPage(pw.Page(
build: (pw.Context context) {
return pw.Center(
child: pw.Text('Dart is awesome', style: pw.TextStyle(font: ttf, fontSize: 40)),
); // Center
})); // Page
To save the pdf file using the path_provider library:
final output = await getTemporaryDirectory();
final file = File('${output.path}/example.pdf');
await file.writeAsBytes(await doc.save());
You can also print the document using the iOS or Android print service:
await Printing.layoutPdf(
onLayout: (PdfPageFormat format) async => doc.save());
Or share the document to other applications:
await Printing.sharePdf(bytes: await doc.save(), filename: 'my-document.pdf');
To print an HTML document:
import HTMLtoPDFWidgets
await Printing.layoutPdf(onLayout: (PdfPageFormat format) async {
const body = '''
<h1>Heading Example</h1>
<p>This is a paragraph.</p>
<img src="image.jpg" alt="Example Image" />
<blockquote>This is a quote.</blockquote>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
''';
final pdf = pw.Document();
final widgets = await HTMLToPdf().convert(body);
pdf.addPage(pw.MultiPage(build: (context) => widgets));
return await pdf.save();
});
Convert a Pdf to images, one image per page, get only pages 1 and 2 at 72 dpi:
await for (var page in Printing.raster(await doc.save(), pages: [0, 1], dpi: 72)) {
final image = page.toImage(); // ...or page.toPng()
print(image);
}
To print an existing Pdf file from a Flutter asset:
final pdf = await rootBundle.load('document.pdf');
await Printing.layoutPdf(onLayout: (_) => pdf.buffer.asUint8List());
Display your PDF document
This package also comes with a PdfPreview widget to display a pdf document.
PdfPreview(
build: (format) => doc.save(),
);
This widget is compatible with Android, iOS, macOS, Linux, Windows and web.
Designing your PDF document
A good starting point is to use PdfPreview which features hot-reload pdf build and refresh.
Take a look at the example tab for a sample project.
Update the _generatePdf method with your design.
Future<Uint8List> _generatePdf(PdfPageFormat format, String title) async {
final pdf = pw.Document();
pdf.addPage(
pw.Page(
pageFormat: format,
build: (context) => pw.Placeholder(),
),
);
return pdf.save();
}
This widget also features a debug switch at the bottom right to display the drawing constraints used. This switch is available only on debug builds.
Moving on to your production application, you can keep the _generatePdf function and print the document using:
final title = 'Flutter Demo';
await Printing.layoutPdf(onLayout: (format) => _generatePdf(format, title));
final doc = pw.Document();
doc.addPage(pw.Page(
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
return pw.Center(
child: pw.Text('Hello World'),
); // Center
})); // Page
Thanks for visiting the tutorial for more tutorials click here.
