dpdf

CI AI Assisted

A pure-Dart toolkit for creating, reading, editing, rendering, compressing, signing, and validating PDF documents. It uses no FFI or external binaries and supports the Dart VM (JIT/AOT), dart2js, and dart2wasm.

How this package was built

Parts of the code, the tests and the documentation were written with the help of LLM tooling. Everything in the package goes through the test suite (dart test), the analyzer (dart analyze) and dart pub publish --dry-run before it lands, and the person who commits it is responsible for it. Treat the disclosure as information about how the work was produced, not as a disclaimer about its quality: the checks are the same either way, and so is the accountability.

import 'package:dpdf/dpdf.dart';

Highlights

  • PDF object model, xref tables and streams, object streams, incremental updates, linearization, encryption, optional content, forms, fonts, and annotations
  • High-level layout with paragraphs, lists, tables, images, and page breaks
  • HTML-to-PDF and SVG-to-PDF conversion
  • PDF page rendering to RGBA pixels or PNG
  • Text extraction in content-stream order (not visual reading order), redaction, page assembly, overlays, and form merging
  • Structural compression and optional image recompression
  • Digital signatures, timestamping, OCSP, CRL, JKS, and BKS support
  • Integrity checks and explicit PDF/A and PDF/UA verification reports

Lay out a document

Document.add is synchronous. It appends the element to the document's queue and returns; every page, every measurement and every bit of drawing happens in close, which must be awaited.

final output = BytesBuilder(copy: false);
final pdf = PdfDocument.create(PdfWriter.fromBytesBuilder(output));
final document = Document(pdf);

document.add(Paragraph('First page.'));
document.add(AreaBreak(AreaBreakType.NEXT_PAGE));
document.add(Paragraph('Second page.'));

await document.close(); // lays everything out, in the order it was added
await pdf.close();

The queue keeps insertion order, so an AreaBreak between two paragraphs still breaks between them. Two consequences follow from the work being deferred: an element must not be mutated after it is added, because close lays out the object as it stands then; and a layout error surfaces from close rather than from add. Closing a PdfDocument while a Document or Canvas built on it still holds queued content is refused with an explicit error, so a forgotten close cannot quietly produce an empty file. Canvas follows the same rule, and showTextAligned queues like add does.

HTML and SVG

final bytes = await HtmlConverter.convertToBytes('''
  <h1>Quarterly report</h1>
  <p>Generated entirely in Dart.</p>
  <table><tr><th>Item</th><th>Value</th></tr>
         <tr><td>Licenses</td><td>12,400</td></tr></table>
''');

final svgPdf = await SvgConverter.convertToBytes('''
  <svg width="200" height="100" viewBox="0 0 200 100">
    <rect x="10" y="10" width="180" height="80"
          fill="#eef" stroke="#225" stroke-width="2"/>
  </svg>
''');

SVG supports svg, g, defs, use, symbol, switch, path, rect, circle, ellipse, line, polyline, polygon, image, text, tspan, textPath, clipPath, mask, marker, pattern and the gradient elements, including transforms, viewBox, fill/stroke styling, opacity, and inline style inheritance.

Render PDF pages

Arbitrary bytes may precede the %PDF- header, as ISO 32000-2 7.5.2 allows, provided the header starts within the first 1024 bytes; PdfReader.headerOffset reports how many were skipped, and rewriting the document drops them.

final document = await PdfDocument.open(PdfReader.fromBytes(input));
final result = await PdfPageRenderer.render(document.getPage(1));
final png = result.toPng();

The renderer handles paths, arbitrary clipping, supported PDF color spaces, image and Form XObjects, masks, embedded font outlines and Type 3 glyph procedures, and honours transparency and text knockout. PdfRenderReport identifies skipped work rather than silently claiming a complete rendering. Applications may provide a font fallback for PDFs that omit font programs. Halftones and the other device-bound entries of clause 10 are deliberately not applied: the output is a continuous-tone surface, and screening it would match no viewer.

Compress documents

final result = await PdfCompressor.compress(input);
print(result.report);

Compression can create object and xref streams, recompress streams, deduplicate objects, and remove unreachable objects. If rewriting would make the document larger, the original bytes are returned unchanged. Continuous-tone images are only changed when explicitly requested:

final result = await PdfCompressor.compress(
  input,
  options: const PdfCompressionOptions(
    images: PdfImageCompressionOptions.lossy(
      quality: 75,
      targetDpi: 150,
      maxDimension: 2400,
    ),
  ),
);

targetDpi follows each image's effective placement through page and Form XObject transformations; a reused image keeps the resolution needed by its largest occurrence. maxDimension can additionally impose an absolute pixel cap. Bi-level images are re-encoded losslessly and the smaller JBIG2 or Flate representation is kept. When several eligible images repeat the same symbols, the compressor can store one shared /JBIG2Globals dictionary and reference it from each image's /DecodeParms; its aggregate size is included in auto selection.

Inspect and validate

final integrity = await PdfIntegrityChecker.inspect(input);
for (final finding in integrity.findings) {
  print(finding);
}

final pdfa = await PdfAVerifier.verify(
  input,
  level: PdfAConformanceLevel.a2b,
);
print(pdfa.violations);
print(pdfa.unverifiedRules);

Integrity checks cover headers, EOF markers, startxref, byte-accurate xref offsets, reachable pages, cycles, truncated streams, and filter failures. Conformance reports are not certifications: unverifiedRules lists checks outside the verifier's scope.

Redact content

final redacted = await PdfAreaRedaction.apply(input, [
  PdfRedactionArea(1, left: 70, bottom: 675, right: 300, top: 693),
]);

Area redaction removes matching text, replaces covered pixels in direct or Form-nested images (cloning shared resources), and deletes vector artwork that falls wholly inside an area, in page content and in nested Form XObjects. A filled path that crosses an area edge is clipped: curves are split at the parameters where they cross, and the hole is closed along the edge itself in the direction that preserves the winding rule, so f (nonzero) and f* (even-odd) both keep their meaning outside. A stroked path that crosses an edge is still refused, because the pen paints half the width to either side of the geometry and clipping the geometry would not erase that ink: a file that only looks redacted is worse than one that admits it cannot be. Clipping paths, shadings and Type 3 glyph procedures are still only covered. PdfTextRedaction offers a stricter reconstruction path and rejects documents it cannot safely rebuild.

CCITT fax support

CCITTFaxDecode decodes Group 4 (K negative), Group 3 one-dimensional (K zero) and mixed Group 3 two-dimensional (K positive) data, honouring EncodedByteAlign, BlackIs1, EndOfLine, Rows and DamagedRowsBeforeError; an absent Rows trims to the lines actually decoded. Encoding writes Group 4. The run-length tables the decoder uses are derived from the ones the encoder writes, so the two cannot drift apart.

JPEG support

JpegDecoder supports baseline and progressive JPEG with either entropy coder — Huffman or arithmetic (SOF9/SOF10) — plus lossless JPEG (SOF3/SOF11) with all seven predictors of Annex H, and hierarchical JPEG built on those lossless processes (Annex J). It handles grayscale, RGB, Adobe CMYK/YCCK, common chroma subsampling, successive approximation, EOB runs, restart markers, 8 and 12 bits per sample, and 16-bit quantisation tables. Differential DCT frames (SOF5, SOF6, SOF13, SOF14) are refused with an explicit message. JpegEncoder writes baseline JPEG with configurable quality and subsampling.

Known limitations

  • Full specification coverage remains pending. JBIG2, CFF/CID, SVG and the other subsystems described below are implemented and tested incrementally, but are not yet considered 100% complete.
  • SVG <style> rules support compound and attribute selectors, all six CSS attribute matching operators, and descendant, child, adjacent-sibling and general-sibling combinators. Structural :root, :empty, :first-child, :last-child, :only-child and :nth-child(An+B) selectors are resolved. Colored tiling patterns and luminance/alpha masks are emitted as native PDF pattern and soft-mask resources. Tiling patterns paint both fills and strokes; axial/radial gradients also paint strokes through native shading patterns. Quoted local url() references and SVG fallback colours are resolved. Gradient stop opacity uses an aligned shading soft mask. Marker viewports support alignment, meet/slice and overflow clipping; some advanced paint-server cases remain partial.
  • PDF rendering draws the fourteen standard fonts from bundled URW Core 35 faces when the document does not embed a program, so a page of Helvetica or Symbol is not blank. The widths still come from the PDF, and PdfRenderReport.fontsSubstituted names every font drawn with another typeface. PdfRenderOptions.useStandardFonts turns that off, useSystemFonts adds the machine's installed catalogue (off by default, since it varies per machine), and fontFallback replaces both; it is also the only route on the web, where the bundled programs are not carried. Composite, Type 3 and unknown symbolic fonts are still reported rather than approximated. CID-keyed CFF supports FDArray/FDSelect and charset CID-to-GID mapping. CFF2 outlines and variable blend charstrings render; BLFont can select normalized non-default variation coordinates. Bare Type1C fonts resolve their internal Standard or Expert CFF Encoding and PDF /Differences through glyph names, without assuming character codes are glyph IDs. Type 2 arithmetic, conditional, transient-storage and stack operators are executed when they feed glyph outlines. Axial/radial PatternType 2 shadings, colored/uncolored tiling patterns and patterned strokes render, including asymmetric shading extension. Type 4 free-form and Type 5 lattice Gouraud meshes render with decoded vertex colours, including parameter interpolation before nonlinear shading functions. Type 6 Coons and Type 7 tensor patches render with bicubic geometry and implicit shared edges. Alpha and luminosity soft masks, backdrop colours and transfer functions render; masks can be replaced or removed without losing the geometric clip. Some advanced transparency-group cases remain partial.
  • Area redaction rewrites inline, direct and Form-nested opaque, transparent and shared image uses. Vector artwork still requires overlay coverage.
  • HTML accepts a BLFontCollection and embeds matching TrueType/OpenType CSS faces. Native applications can populate it with BLFontLoader.loadSystemFonts from package:dgfx/dgfx_io.dart; web clients can attach a BLCallbackFontProvider backed by URLs, Google Fonts or FontFace. CSS @font-face URLs and data URIs can be loaded through HtmlConverterProperties.fontResourceLoader and baseUri; local() resolves installed/catalogued faces without downloading a fallback. WOFF 1.0 and WOFF 2.0 are both decoded to sfnt, the latter including the glyf/loca and hmtx transformations and ttcf collections, with a Brotli decoder bundled in the package rather than an FFI binding. ttcf collections are reconstructed correctly but the sfnt reader does not yet open a collection.
  • JBIG2 automatically chooses between generic regions and deduplicated symbol dictionaries with text regions, including shared /JBIG2Globals across PDF images. Lossless refinement aggregation for near-identical glyphs works for single images and shared cross-page /JBIG2Globals dictionaries; the encoder keeps it only when the complete representation is smaller.

Optional reading, recovery, merge, and signing modes are documented in test/compatibility/OPTIONAL_MODES.md.

Development

dart analyze
dart test
dart run tool/check_platforms.dart

The platform check covers VM/JIT, VM/AOT, dart2js, and dart2wasm; Wasm requires Node.js with WasmGC support. To regenerate the embedded Adobe glyph and standard-font metric resources, run dart run tool/generate_font_resources.dart. dart run tool/generate_standard_fonts.dart regenerates the embedded URW programs from assets/fonts/urw-core35/ into lib/src/render/resources/standard_font_programs_vm.dart, which carries them gzipped and base64-encoded. That file is generated: edit the tool, never it. It is reached through the conditional facade lib/src/render/standard_fonts.dart, so the programs load on the VM and are absent from a web build.

License

MIT for the code. The package also bundles fourteen faces of the URW Core 35 (version 2.00) under the SIL Open Font License 1.1, Copyright (c) 2014,2015 by (URW)++ Design & Development, used to draw the fourteen standard PDF fonts when a document references them without embedding a program; the copyright statement declares no Reserved Font Name. The full licence text travels in THIRD_PARTY_NOTICES.md; the original .otf files and their LICENSE.OFL live in assets/fonts/urw-core35/ in the repository, which is not part of the published package. See THIRD_PARTY_NOTICES.md for this and the other notices covering embedded third-party data.

Libraries

dpdf
dpdf a dart PDF library
dpdf_platform
Platform capabilities for applications embedding DPDF.
dpdf_web
Browser file registration and output bytes for dart2js and dart2wasm hosts.