dart_pdf

repository·master·Indexed 23 days ago

https://github.com/davbfr/dart_pdf

A suite of Dart and Flutter plugins for PDF generation and printing on iOS, Android, Windows, Linux, macOS, and Web. It includes a widget-based system for document construction, support for TrueType fonts, Google Fonts, and emojis, and capabilities for creating PDF/A compliant documents with Factur-X embedding. The accompanying printing plugin enables platform-specific print/preview dialogs and PDF.js integration for web.

Tokens
12.3K
Snippets
26
Records
65
Agent score
80%

What's inside dart_pdf

  1. Embed Flutter Widgets into PDF documents with pdf_widget_wrapper

    master
    The pdf_widget_wrapper plugin provides a mechanism to embed standard Flutter Widgets directly into a PDF document. This allows you to leverage the full power of the Flutter widget tree (including layout, styling, and complex UI components) when generating PDF content, rather than relying solely on the low-level PDF drawing primitives.
  2. Generate and print PDFs in Flutter

    master

    The dart_pdf ecosystem provides two primary packages for handling PDF workflows in Flutter applications on iOS and Android:

    1. pdf: Used for generating PDF documents programmatically.
    2. printing: Used for printing those generated PDF files to a device printer or displaying them in a print preview.

    To use these in your project, add them to your pubspec.yaml dependencies.

  3. How MultiPage (automatic pagination) works

    master

    The pw.MultiPage widget automatically flows content across multiple pages, creating page breaks when content exceeds the available space.

    Key Concepts

    • Automatic Page Breaks: New pages are created when children don't fit.
    • Headers and Footers: These are defined per page. Their space is reserved before the main content is laid out.
    • Spanning vs. Inseparable Widgets:
      • Spanning Widgets: pw.Flex, pw.Partition, pw.Table, pw.Wrap, pw.GridView, and pw.Column can split across page boundaries.
      • Inseparable Widgets: Use pw.Inseparable to wrap content that must stay together on a single page. If the content doesn't fit, it will trigger a page break.
    • Manual Page Breaks: Use pw.NewPage() to force a break. You can provide freeSpace (e.g., pw.NewPage(freeSpace: 40)) to only break if less than that amount of space remains.
    • Safety: A maxPages limit (default 20) is enforced in debug mode to prevent infinite loops during pagination.
    pdf.addPage(pw.MultiPage(
      pageFormat: PdfPageFormat.a4,
      header: (context) => pw.Padding(
        padding: const pw.EdgeInsets.only(bottom: 8),
        child: pw.Text('Document Header'),
      ),
      footer: (context) => pw.Padding(
        padding: const pw.EdgeInsets.only(top: 8),
        child: pw.Row(
          mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
          children: [
            pw.Text('Footer'),
            pw.Text('Page ${context.pageNumber} of ${context.pagesCount}'),
          ],
        ),
      ),
      build: (context) => [
        pw.Text('Section 1: Introduction'),
        pw.SizedBox(height: 20),
    
        // Spanning content
        pw.Wrap(
          spacing: 8,
          runSpacing: 8,
          children: List.generate(50, (i) => pw.Container(
            padding: const pw.EdgeInsets.all(8),
            decoration: pw.BoxDecoration(
              border: pw.Border.all(),
              borderRadius: const pw.BorderRadius.all(pw.Radius.circular(4)),
            ),
            child: pw.Text('Item $i'),
          )),
        ),
    
        pw.NewPage(), // Force page break
    
        // Inseparable content
        pw.Inseparable(
          child: pw.Column(
            crossAxisAlignment: pw.CrossAxisAlignment.start,
            children: [
              pw.Text('• This content must stay together'),
              pw.Text('• It cannot be split across pages'),
            ],
          ),
        ),
      ],
    ));
  4. Coordinate system and units

    master

    The coordinate system uses internal PDF units where 1.0 is defined as 1/72.0 of an inch.

    You can use predefined constants for common measurements like centimeters, millimeters, and inches provided in PdfPageFormat.

  5. Install the printing plugin

    master

    To use the printing plugin in your Flutter project, follow these steps:

    1. Add printing to your pubspec.yaml.
    2. Import the necessary libraries:
      import 'package:pdf/pdf.dart';
      import 'package:pdf/widgets.dart' as pw;
      import 'package:printing/printing.dart';
    3. iOS Setup: In ios/Podfile, ensure use_frameworks! is enabled within the target 'Runner' block.
    4. macOS Setup: Add the com.apple.security.print entitlement to both macos/Runner/Release.entitlements and macos/Runner/DebugProfile.entitlements.
    5. Web Setup: If you need to manually set the Pdf.js version or base URL, add a script to web/index.html before the </head> tag.
    6. Windows/Linux Setup: You can force the pdfium version and architecture in your main CMakeLists.txt using set(PDFIUM_VERSION ...) and set(PDFIUM_ARCH ...).
    import 'package:pdf/pdf.dart';
    import 'package:pdf/widgets.dart' as pw;
    import 'package:printing/printing.dart';
  6. Install the dart_pdf library

    master

    To use the library in your Dart or Flutter project, add it to your pubspec.yaml file. For full Flutter printing and sharing capabilities, it is recommended to also use the printing package.

    After installation, import the core PDF library and the Widgets system (aliased as pw for convenience):

    import 'package:pdf/pdf.dart';
    import 'package:pdf/widgets.dart' as pw;
  7. Create PDF/A compliant PDFs

    master

    To create a PDF/A compliant document using this library, you must adhere to several requirements regarding fonts, metadata, and color profiles.

    Requirements:

    1. Embedded Fonts: The PDF must only use embedded fonts.
    2. No Annotations: Currently, annotations cannot be used in PDF/A compliant documents.
    3. Metadata: You must include a special Meta-XML. Use the PdfaRdf class and insert the resulting XML into your document's metadata.
    4. Color Profile: You must include a color profile. Use the PdfaColorProfile class and embed the contents of an ICC profile (e.g., sRGB2014.icc).
    5. Factur-X (Optional): You can optionally attach an InvoiceXML using PdfaFacturxRdf and PdfaAttachedFiles.
  8. Run the PDF Printing Demo

    master

    To run the detailed PDF printing example, you must first ensure that all necessary assets (fonts and graphics) are downloaded using the provided Makefile.

    Prerequisites for Windows users: You must have make installed. The easiest way to install it is via Chocolatey:

    choco install make

    Setup and Execution Steps:

    1. Clone the repository:
      git clone https://github.com/DavBfr/dart_pdf.git
    2. Navigate to the directory and fetch assets:
      cd dart_pdf
      make get-all
    3. Run the demo for your target platform:
      • Windows: flutter run -d windows
      • Linux: flutter run -d linux
      • macOS: flutter run -d macos
    git clone https://github.com/DavBfr/dart_pdf.git
    cd dart_pdf
    make get-all
    flutter run -d windows
  9. Customize the iOS launch screen assets

    master

    To change the launch screen image for the iOS version of your Flutter app, you can use one of two methods:

    1. Direct File Replacement: Replace the existing image files located in the demo/ios/Runner/Assets.xcassets/LaunchImage.imageset/ directory with your own assets.
    2. Xcode Interface:
      • Open the iOS project in Xcode by running open ios/Runner.xcworkspace from your terminal.
      • In the Xcode Project Navigator, navigate to Runner/Assets.xcassets.
      • Drag and drop your desired images into the asset catalog to replace the launch screen assets.
    open ios/Runner.xcworkspace
  10. Configure Pdf.js for Web

    master

    By default, Pdf.js is loaded automatically on the web. However, you can manually configure it in web/index.html by adding a script before the </head> tag.

    To set a specific version:

    <script>
      var dartPdfJsVersion = "3.2.146";
    </script>

    To set an alternative location (CDN or local directory):

    <script>
      var dartPdfJsBaseUrl = "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.2.146/";
    </script>

    Example using a local directory:

    <script>
      var dartPdfJsBaseUrl = "assets/js/pdf/3.2.146/";
    </script>
  11. Configure PDF opening behavior with PdfPageMode

    master

    The PdfPageMode enum defines how a PDF viewer should initially display the document when it is opened:

    • PdfPageMode.none: The default mode. Only the page is visible.
    • PdfPageMode.outlines: Displays the document outlines (bookmarks) upon opening.
    • PdfPageMode.thumbs: Displays thumbnails upon opening.
    • PdfPageMode.fullscreen: Opens the document in full-screen mode without menus or window controls.