pdf 1.6.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 98

Pdf creation library for dart/flutter #

This library is divided into two parts:

  • a low-level Pdf creation library that takes care of the pdf bits generation.
  • a Widgets system similar to Flutter's, for easy high-level Pdf creation.

It can create a full multi-pages document with graphics, images, and text using TrueType fonts. With the ease of use you already know.

Example document

Use the printing package https://pub.dev/packages/printing for full flutter print and share operation.

The coordinate system is using the internal Pdf unit:

  • 1.0 is defined as 1 / 72.0 inch
  • you can use the constants for centimeters, millimeters, and inch defined in PdfPageFormat

Buy Me A Coffee

Installing #

If you want to print the Pdf document on an actual printer with Flutter, follow the instructions at https://pub.dev/packages/printing

  1. Add this package to your package's pubspec.yaml file as described on the installation tab

  2. Import the libraries

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

Examples #

final pdf = pw.Document();

      pageFormat: PdfPageFormat.a4,
      build: (pw.Context context) {
        return pw.Center(
          child: pw.Text("Hello World"),
        ); // Center
      })); // Page

To load an image from a file:

final image = PdfImage.file(
  bytes: File('test.webp').readAsBytesSync(),

    build: (pw.Context context) {
      return pw.Center(
        child: pw.Image(image),
      ); // Center
    })); // Page

To use a TrueType font:

final Uint8List fontData = File('open-sans.ttf').readAsBytesSync();
final ttf = pw.Font.ttf(fontData.buffer.asByteData());

    pageFormat: PdfPageFormat.a4,
    build: (pw.Context context) {
      return pw.Center(
        child: pw.Text('Hello World', style: pw.TextStyle(font: ttf, fontSize: 40)),
      ); // Center
    })); // Page

To save the pdf file:

// 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(pdf.save());

Encryption and Digital Signature #

Encryption using RC4-40, RC4-128, AES-128, and AES-256 is fully supported using a separate library. This library also provides SHA1 or SHA-256 Digital Signature using your x509 certificate. The graphic signature is represented by a clickable widget that shows Digital Signature information.

Drop me an email for availability and more information.

Changelog #

1.6.0 #

  • Improve Annotations
  • Implement table row vertical alignment
  • Improve Internal data structure
  • Remove deprecated functions
  • Optimize file size
  • Add PdfColor.shade
  • Uniformize examples
  • Fix context painting empty Table
  • Fix Text decoration placements
  • Improve image buffer management
  • Optimize memory footprint
  • Add an exception if a jpeg image is not a supported format
  • Add more image loading functions

1.5.0 #

  • Fix Align debug painting
  • Fix GridView when empty
  • Reorder MultiPage paint operations
  • Fix Bullet widget styling
  • Fix HSV and HSL Color constructors
  • Add PageTheme.copyWith
  • Add more font drawing options
  • Add Opacity Widget
  • Fix Text height with TrueType fonts
  • Convert Flex to a SpanningWidget
  • Add Partitions Widget
  • Fix a TrueType parser issue with some Chinese fonts

1.4.1 #

  • Update dependency to barcode ^1.5.0
  • Update type1 font warning URL
  • Fix Image fit

1.4.0 #

  • Improve BarcodeWidget
  • Fix BarcodeWidget positioning
  • Update dependency to barcode ^1.4.0

1.3.29 #

  • Use Barcode stable API

1.3.28 #

  • Add Barcode Widget
  • Add QrCode Widget

1.3.27 #

  • Add Roll Paper support
  • Implement custom table widths

1.3.26 #

  • Update Analysis options

1.3.25 #

  • Add more warnings on type1 fonts
  • Simplify PdfImage constructor
  • Implement Image orientation
  • Add Exif reader
  • Add support for GreyScale Jpeg
  • Add FullPage widget

1.3.24 #

  • Update Web example
  • Add more color functions
  • Fix Pdf format
  • Fix warning in tests
  • Fix warning in example
  • Format Java code
  • Add optional clipping on Page
  • Add Footer Widget
  • Fix Page orientation
  • Add Ascii85 test

1.3.23 #

  • Implement ListView.builder and ListView.separated

1.3.22 #

  • Fix Text alignment
  • Fix Theme creation

1.3.21 #

  • Add TextDecoration

1.3.20 #

  • Fix Transform.rotateBox
  • Add Watermark widget
  • Add PageTheme

1.3.19 #

  • Fix Ascii85 encoding

1.3.18 #

  • Implement InlineSpan and WidgetSpan
  • Fix Theme.withFont factory
  • Implement InheritedWidget
  • Fix Web dependency
  • Add Web example

1.3.17 #

  • Fix MultiPage with multiple save() calls

1.3.16 #

  • Add better debug painting on Align Widget
  • Fix Transform placement when Alignment and Origin are Null
  • Add Transform.rotateBox constructor
  • Add Wrap Widget

1.3.15 #

  • Fix Image shape inside BoxDecoration

1.3.14 #

  • Add Document ID
  • Add encryption support
  • Increase PDF version to 1.7
  • Add document signature support
  • Default compress output if available

1.3.13 #

  • Do not modify the TTF font streams

1.3.12 #

  • Fix TextStyle constructor

1.3.11 #

  • Update Readme

1.3.10 #

  • Deprecate the document argument in Printing.sharePdf()
  • Add a default value to alpha in PdfColor variants
  • Fix Table Widget
  • Add Flexible and Spacer Widgets

1.3.9 #

  • Fix Transform Widget alignment
  • Fix CustomPaint Widget size
  • Add DecorationImage to BoxDecoration
  • Add default values to ClipRRect

1.3.8 #

  • Add jpeg image loading function
  • Add Theme::copyFrom() method
  • Allow Annotations in TextSpan
  • Add SizedBox Widget
  • Fix RichText Widget word spacing
  • Improve Theme and TextStyle
  • Implement properly RichText.softWrap
  • Set a proper value to context.pagesCount

1.3.7 #

  • Add Pdf Creation date
  • Support 64k glyphs per TTF font

1.3.6 #

  • Fix TTF Font SubSetting

1.3.5 #

  • Add some color functions
  • Remove color constants from PdfColor, use PdfColors
  • Add TTF Font SubSetting
  • Add Unicode support for TTF Fonts
  • Add Circular Progress Indicator

1.3.4 #

  • Add available dimensions for PdfPageFormat
  • Add Document properties
  • Add Page.orientation to force landscape or portrait
  • Improve MultiPage Widget
  • Convert GridView to a SpanningWidget
  • Add all Material Colors
  • Add Hyperlink widgets

1.3.3 #

  • Fix a bug with the RichText Widget
  • Update code to Dart 2.1.0
  • Add Document.save() method

1.3.2 #

  • Fix dart lint warnings
  • Improve font bounds calculation
  • Add RichText Widget
  • Fix MultiPage max-height
  • Add Stack Widget
  • Update Readme

1.3.1 #

  • Fix pana linting notices

1.3.0 #

  • Add a Flutter-like Widget system

1.2.0 #

  • Change license to Apache 2.0
  • Improve PdfRect
  • Add support for CMYK, HSL and HSV colors
  • Implement rounded rect

1.1.1 #

  • Improve PdfPoint and PdfRect
  • Change PdfColor.fromInt to const constructor
  • Fix drawShape Bézier curves
  • Add arcs to SVG drawShape
  • Add default page margins
  • Change license to Apache 2.0

1.1.0 #

  • Rename classes to satisfy Dart conventions
  • Remove useless new and const keywords
  • Mark some internal functions as protected
  • Fix annotations
  • Implement default fonts bounding box
  • Add Bézier Curve primitive
  • Implement drawShape
  • Add support for Jpeg images
  • Fix numeric conversions in graphic operations
  • Add Unicode support for annotations and info block
  • Add Flutter example

1.0.8 #

  • Fix monospace TTF font loading
  • Add PDFPageFormat::toString

1.0.7 #

  • Use lowercase page dimension constants

1.0.6 #

  • Fix TTF font name lookup

1.0.5 #

  • Remove dependency to dart:io
  • Add Contributing

1.0.4 #

  • Updated homepage
  • Update source formatting
  • Update README

1.0.3 #

  • Remove dependency to ttf_parser

1.0.2 #

  • Update SDK support for 2.0.0

1.0.1 #

  • Add example
  • Lower vector_math dependency version
  • Uses better page format object

1.0.0 #

  • Initial version


// ignore_for_file: omit_local_variable_types

import 'dart:io';

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

void main() {
  final pw.Document doc = pw.Document();

          PdfPageFormat.letter.copyWith(marginBottom: 1.5 * PdfPageFormat.cm),
      crossAxisAlignment: pw.CrossAxisAlignment.start,
      header: (pw.Context context) {
        if (context.pageNumber == 1) {
          return null;
        return pw.Container(
            alignment: pw.Alignment.centerRight,
            margin: const pw.EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
            padding: const pw.EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),
            decoration: const pw.BoxDecoration(
                border: pw.BoxBorder(
                    bottom: true, width: 0.5, color: PdfColors.grey)),
            child: pw.Text('Portable Document Format',
                style: pw.Theme.of(context)
                    .copyWith(color: PdfColors.grey)));
      footer: (pw.Context context) {
        return pw.Container(
            alignment: pw.Alignment.centerRight,
            margin: const pw.EdgeInsets.only(top: 1.0 * PdfPageFormat.cm),
            child: pw.Text(
                'Page ${context.pageNumber} of ${context.pagesCount}',
                style: pw.Theme.of(context)
                    .copyWith(color: PdfColors.grey)));
      build: (pw.Context context) => <pw.Widget>[
                level: 0,
                child: pw.Row(
                    mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
                    children: <pw.Widget>[
                      pw.Text('Portable Document Format', textScaleFactor: 2),
                    'The Portable Document Format (PDF) is a file format developed by Adobe in the 1990s to present documents, including text formatting and images, in a manner independent of application software, hardware, and operating systems. Based on the PostScript language, each PDF file encapsulates a complete description of a fixed-layout flat document, including the text, fonts, vector graphics, raster images and other information needed to display it. PDF was standardized as an open format, ISO 32000, in 2008, and no longer requires any royalties for its implementation.'),
                    'Today, PDF files may contain a variety of content besides flat text and graphics including logical structuring elements, interactive elements such as annotations and form-fields, layers, rich media (including video content) and three dimensional objects using U3D or PRC, and various other data formats. The PDF specification also provides for encryption and digital signatures, file attachments and metadata to enable workflows requiring these features.'),
            pw.Header(level: 1, text: 'History and standardization'),
                    "Adobe Systems made the PDF specification available free of charge in 1993. In the early years PDF was popular mainly in desktop publishing workflows, and competed with a variety of formats such as DjVu, Envoy, Common Ground Digital Paper, Farallon Replica and even Adobe's own PostScript format."),
                    'PDF was a proprietary format controlled by Adobe until it was released as an open standard on July 1, 2008, and published by the International Organization for Standardization as ISO 32000-1:2008, at which time control of the specification passed to an ISO Committee of volunteer industry experts. In 2008, Adobe published a Public Patent License to ISO 32000-1 granting royalty-free rights for all patents owned by Adobe that are necessary to make, use, sell, and distribute PDF compliant implementations.'),
                    "PDF 1.7, the sixth edition of the PDF specification that became ISO 32000-1, includes some proprietary technologies defined only by Adobe, such as Adobe XML Forms Architecture (XFA) and JavaScript extension for Acrobat, which are referenced by ISO 32000-1 as normative and indispensable for the full implementation of the ISO 32000-1 specification. These proprietary technologies are not standardized and their specification is published only on Adobe's website. Many of them are also not supported by popular third-party implementations of PDF."),
                    'On July 28, 2017, ISO 32000-2:2017 (PDF 2.0) was published. ISO 32000-2 does not include any proprietary technologies as normative references.'),
            pw.Header(level: 1, text: 'Technical foundations'),
            pw.Paragraph(text: 'The PDF combines three technologies:'),
                    'A subset of the PostScript page description programming language, for generating the layout and graphics.'),
                    'A font-embedding/replacement system to allow fonts to travel with the documents.'),
                    'A structured storage system to bundle these elements and any associated content into a single file, with data compression where appropriate.'),
            pw.Header(level: 2, text: 'PostScript'),
                    'PostScript is a page description language run in an interpreter to generate an image, a process requiring many resources. It can handle graphics and standard features of programming languages such as if and loop commands. PDF is largely based on PostScript but simplified to remove flow control features like these, while graphics commands such as lineto remain.'),
                    'Often, the PostScript-like PDF code is generated from a source PostScript file. The graphics commands that are output by the PostScript code are collected and tokenized. Any files, graphics, or fonts to which the document refers also are collected. Then, everything is compressed to a single file. Therefore, the entire PostScript world (fonts, layout, measurements) remains intact.'),
                crossAxisAlignment: pw.CrossAxisAlignment.start,
                children: <pw.Widget>[
                          'As a document format, PDF has several advantages over PostScript:'),
                          'PDF contains tokenized and interpreted results of the PostScript source code, for direct correspondence between changes to items in the PDF page description and changes to the resulting page appearance.'),
                          'PDF (from version 1.4) supports graphic transparency; PostScript does not.'),
                          'PostScript is an interpreted programming language with an implicit global state, so instructions accompanying the description of one page can affect the appearance of any following page. Therefore, all preceding pages in a PostScript document must be processed to determine the correct appearance of a given page, whereas each page in a PDF document is unaffected by the others. As a result, PDF viewers allow the user to quickly jump to the final pages of a long document, whereas a PostScript viewer needs to process all pages sequentially before being able to display the destination page (unless the optional PostScript Document Structuring Conventions have been carefully complied with).'),
            pw.Header(level: 1, text: 'Content'),
                    'A PDF file is often a combination of vector graphics, text, and bitmap graphics. The basic types of content in a PDF are:'),
                    'Text stored as content streams (i.e., not encoded in plain text)'),
                    'Vector graphics for illustrations and designs that consist of shapes and lines'),
                    'Raster graphics for photographs and other types of image'),
            pw.Bullet(text: 'Multimedia objects in the document'),
                    'In later PDF revisions, a PDF document can also support links (inside document or web page), forms, JavaScript (initially available as plugin for Acrobat 3.0), or any other types of embedded contents that can be handled using plug-ins.'),
                    'PDF 1.6 supports interactive 3D documents embedded in the PDF - 3D drawings can be embedded using U3D or PRC and various other data formats.'),
                    'Two PDF files that look similar on a computer screen may be of very different sizes. For example, a high resolution raster image takes more space than a low resolution one. Typically higher resolution is needed for printing documents than for displaying them on screen. Other things that may increase the size of a file is embedding full fonts, especially for Asiatic scripts, and storing text as graphics. '),
                level: 1, text: 'File formats and Adobe Acrobat versions'),
                    'The PDF file format has changed several times, and continues to evolve, along with the release of new versions of Adobe Acrobat. There have been nine versions of PDF and the corresponding version of the software:'),
            pw.Table.fromTextArray(context: context, data: const <List<String>>[
              <String>['Date', 'PDF Version', 'Acrobat Version'],
              <String>['1993', 'PDF 1.0', 'Acrobat 1'],
              <String>['1994', 'PDF 1.1', 'Acrobat 2'],
              <String>['1996', 'PDF 1.2', 'Acrobat 3'],
              <String>['1999', 'PDF 1.3', 'Acrobat 4'],
              <String>['2001', 'PDF 1.4', 'Acrobat 5'],
              <String>['2003', 'PDF 1.5', 'Acrobat 6'],
              <String>['2005', 'PDF 1.6', 'Acrobat 7'],
              <String>['2006', 'PDF 1.7', 'Acrobat 8'],
              <String>['2008', 'PDF 1.7', 'Acrobat 9'],
              <String>['2009', 'PDF 1.7', 'Acrobat 9.1'],
              <String>['2010', 'PDF 1.7', 'Acrobat X'],
              <String>['2012', 'PDF 1.7', 'Acrobat XI'],
              <String>['2017', 'PDF 2.0', 'Acrobat DC'],
            pw.Padding(padding: const pw.EdgeInsets.all(10)),
                    'Text is available under the Creative Commons Attribution Share Alike License.')

  final File file = File('example.pdf');

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  pdf: ^1.6.0

2. Install it

You can install packages from the command line:

with pub:

$ pub get

with Flutter:

$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:pdf/pdf.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on Mar 28, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.3.0 <3.0.0
archive ^2.0.10 2.0.13
barcode ^1.5.0 1.5.0
crypto ^2.0.6 2.1.4
image ^2.1.4 2.1.12
meta ^1.1.5 1.1.8
qr ^1.2.0 1.2.0
utf ^0.9.0 0.9.0+5
vector_math ^2.0.0 2.0.8
Transitive dependencies
args 1.6.0
charcode 1.1.3
collection 1.14.12
convert 2.1.1
path 1.6.4
petitparser 3.0.1
typed_data 1.1.6
xml 3.7.0
Dev dependencies
pedantic 1.9.0
test any