pdf_graphics library

Content-stream parsing and interpretation for PDF pages: the interpreter walks page content and emits drawing callbacks into a PdfDevice implementation (Flutter Canvas, text extraction, test recorders).

Classes

ContentOperation
One content-stream instruction: operands followed by an operator.
ContentStreamParser
Parses a page content stream into a flat list of operations.
IccProfile
An ICC profile reduced to what rendering needs: a transform from device components to sRGB.
PdfAnnotationContext
One annotation summarized for an agent.
PdfBeginGroupCommand
PdfDevice.beginGroup.
PdfBeginSoftMaskedCommand
PdfDevice.beginSoftMasked.
PdfCalibratedColorSpace
CIE-based calibrated color spaces used by PDF graphics operators.
PdfCancellationToken
Cooperative cancellation for in-flight interpreter walks.
PdfClipPathCommand
PdfDevice.clipPath.
PdfClosePath
PdfColor
An RGB color with components in 0..1, the renderer's common currency. Device color spaces convert into it; ICC-based spaces approximate for now.
PdfColorants
A device colorant vector: the four process tints plus a sorted list of named spot colorants and their tints. All tints are 0..1, where 0 is "no ink" - so none (all zero) is bare paper.
PdfColorSpace
A PDF colour space (§8.6) resolved to what rendering needs: how many components a colour carries, and how those components become sRGB.
PdfCubicTo
PdfDecodedPixels
A fully decoded image: premultiplied RGBA8888, ready to hand straight to decodeImageFromPixels with no further per-pixel work. decodePdfImagePixels produces this for every image it can decode without the platform codec.
PdfDevice
Rendering target. The interpreter walks a content stream and emits these callbacks; implementations include the Flutter Canvas device, a text-extraction device, and test recorders.
PdfDocumentActionSink
The write half of the Document-AI seam: the editing actions an agent can drive, decoupled from any particular model or transport.
PdfDocumentContext
A clean, serializable snapshot of a document's text and interactive structure, shaped for handing to a language model.
PdfDrawImageCommand
PdfDevice.drawImage.
PdfDrawTextCommand
PdfDevice.drawText.
PdfDrawTiledCellCommand
A tiling-pattern (or Type3-glyph) cell recorded once and replayed at many page-space positions (#524). cellCommands is the cell's full device transcript at the base position; originsX/originsY are the page-space deltas of every repeat, base first at (0, 0). Devices that understand the command natively implement PdfTiledCellSink (a canvas backend can build one sub-picture and stamp it per origin); everything else gets the exact per-tile expansion from replayCommands via TranslatingPdfDevice.
PdfEndGroupCommand
PdfDevice.endGroup.
PdfEndSoftMaskedCommand
PdfDevice.endSoftMasked. The drawMask closure's device calls are captured in maskCommands; replay rebuilds the closure as a nested replayCommands over them.
PdfExtractedRun
One positioned run of text on a page, in page space.
PdfFieldContext
One interactive form field, flattened for an agent.
PdfFillMeshCommand
PdfDevice.fillMesh.
PdfFillPathCommand
PdfDevice.fillPath.
PdfFillPathGradientCommand
PdfDevice.fillPathGradient.
PdfFontInfo
Metrics, text decoding, and (for embedded TrueType fonts) real glyph outlines for one font dictionary. Fonts without usable embedded outlines fall back to device-side substitution scaled to these widths.
PdfFunction
A PDF function (§7.10), one input except where shadings need more.
PdfGlyphPlacement
One glyph within a PdfTextRun: its outline (when the font is embedded and parsed) and its pen offset, both in em units.
PdfGradient
A gradient ready for a device: stops pre-sampled from the shading's function, with geometry in the space mapped by transform.
PdfImageBase
The base image samples decoded to straight-alpha RGBA, with no /SMask or stencil /Mask applied yet. decodePdfImageBase produces this; the caller bakes in the mask (which may need the platform codec for a DCT /SMask) and premultiplies.
PdfImageColorants
The device colorants an image XObject's samples carry.
PdfImageDecodeCache
Remembers decoded image pixels between serializeCommands calls, so a page recorded more than once does not pay its image decode more than once.
PdfImageRegion
A rectangular source-pixel region of an image, in the top-left origin of decoded samples (the same coordinates a decode produces). Hand one to decodePdfImage to decode only the visible slice of a large raster.
PdfImageRequest
An image draw request. Decoding is left to the device, which may have platform codecs (and may need to be async - devices can pre-collect).
PdfImageSoftMask
A grayscale alpha plane lifted from an /SMask or stencil /Mask (§11.6.5.2 / §8.9.6.3), to be baked into a base image's alpha channel.
PdfInkColorants
A paint's colorants together with the overprint semantics of the colour space it came from - everything over needs to decide which of the device's colorants this ink writes.
PdfInterpreter
Executes page content streams against a PdfDevice.
PdfLineTo
PdfLogicalNode
A node of the logical structure tree with its tagged text filled in.
PdfMatrix
A 2D affine transform in PDF convention: row vectors, so a point maps as x' = a·x + c·y + e, y' = b·x + d·y + f (ISO 32000-1 §8.3.3).
PdfMesh
A triangle mesh with per-vertex colors - the decoded form of mesh shadings (types 4–7). Patch meshes arrive pre-subdivided; devices only ever see Gouraud triangles.
PdfMeshParser
Decodes the bit-packed vertex/patch data of mesh shadings.
PdfMeshVertex
One mesh vertex in page space.
PdfMoveTo
PdfOverprintCompositor
Resolves overprint against a colorant buffer for one page.
PdfPageContentWalk
A resumable walk of one page's content stream, from PdfInterpreter.beginPageContent.
PdfPageContext
One page's textual content and geometry, for PdfDocumentContext.
PdfPageText
The text content of one page, with geometry for search highlighting.
PdfPageTextCache
A persistent cache of extracted page text, on top of a PdfDiskCache.
PdfPath
PdfPathSegment
Path geometry emitted by the interpreter. Coordinates are already transformed into page space (PDF default user space, y-up), because PDF applies the CTM at path-construction time.
PdfReflowBlock
One paragraph-like block in reading order.
PdfReflowDocument
Document-level convenience wrapper for reflowed text.
PdfReflowImage
An image or diagram placed on the page, surfaced in the reflow view in reading order. The pixels are not decoded here (pdf_graphics is VM-only); decode request with the renderer's decodeImages to display it.
PdfReflowItem
One item in a reflowed page, placed in inferred reading order: either a text PdfReflowBlock or a PdfReflowImage.
PdfReflowLine
A line of text inferred from positioned page text.
PdfReflowPage
A page's content reduced to text paragraph blocks and images in inferred reading order.
PdfRenderCommand
A flattened, replayable record of one PdfDevice call.
PdfRestoreCommand
Q - PdfDevice.restore.
PdfSaveCommand
q - PdfDevice.save.
PdfSetBlendModeCommand
PdfDevice.setBlendMode.
PdfSetOverprintCommand
PdfDevice.setOverprint.
PdfShading
A parsed shading dictionary (§8.7.4.5).
PdfStroke
Stroke parameters, with width already scaled into page space.
PdfStrokePathCommand
PdfDevice.strokePath.
PdfTaggedDocument
The whole document's logical structure with text joined in.
PdfTaggedText
Joins a document's structure tree to its extracted text.
PdfTextDiff
A word-level diff of two pages' extracted text, computed as a longest common subsequence over their token streams (a standard sequence diff), with each changed token mapped back to its page-space bounds for highlight overlays.
PdfTextDiffHunk
A contiguous change - one or more adjacent non-PdfTextDiffKind.equal segments, the unit a diff navigator steps through. A pure replace is a delete next to an insert, so a hunk carries both before and after tokens.
PdfTextDiffSegment
One run of the alignment between two pages' token streams.
PdfTextExtractor
Extracts positioned text by running the interpreter with a collecting device - the same code path rendering uses, so what you search is what you see.
PdfTextMatch
One search hit, with page-space geometry for highlighting.
PdfTextQuad
Four page-space corners of a text span's highlight box, in perimeter order: lower-left, lower-right, upper-right, upper-left of the run's own baseline frame.
PdfTextReflower
Paragraph and reading-order inference over PdfPageText.
PdfTextRun
One run of text from a single show-text operator.
PdfTextToken
A whitespace-delimited token of page text, with the page-space box it covers - the unit a PdfTextDiff aligns and the bounds a viewer highlights when it flags the token as changed.
PdfTiledCellSink
Optional capability interface for devices that can consume a PdfDrawTiledCellCommand natively instead of replaying its per-tile expansion. The interpreter and replayCommands probe for it with is.
RecordingPdfDevice
A PdfDevice that records every interpreter callback into a flat, replayable commands list instead of painting.
TranslatingPdfDevice
Forwards every PdfDevice call to target with all page-space geometry translated by (dx, dy).
VectorPrintOp
One replayable op.
VectorPrintPage
A decoded vector-print page: its device-point size and the flat op list.
VpClipPath
VpClose
VpColor
An RGBA colour, 0-255 per channel.
VpCubic
VpFillPath
VpImage
VpLine
VpMove
VpPath
A path in device points: a flat list of subpath commands.
VpRestore
VpSave
VpSegment
VpStrokePath
VpText

Enums

PdfBlendMode
PDF blend modes (§11.3.5). Devices map these to their compositor.
PdfFillRule
PdfTextDiffKind
What a PdfTextDiffSegment represents.

Constants

kColorantBlack → const int
kColorantCyan → const int
Bit per process colorant in PdfInkColorants.processMask.
kColorantMagenta → const int
kColorantProcessAll → const int
kColorantYellow → const int
kVectorPrintFontBold → const int
Font-style flags packed into the text op's flag byte.
kVectorPrintFontItalic → const int
kVectorPrintMagic → const List<int>
Magic + version header of a vector-print stream (VPR + version 1).

Properties

deserializeCommandsMicros int
Microseconds spent reconstructing worker command buffers on the consuming isolate. Accumulated for performance probes; this is the UI-thread half of the record path and intentionally mirrors decodeStripPlanMicros.
getter/setter pair

Functions

cappedImagePixelSize(int srcWidth, int srcHeight, double widthPts, double heightPts, double ratio, {double headroom = 2.0, int maxPixels = 1 << 24, double maxDimension = 8192}) → (int, int)
The pixel size an image should be decoded/stored at so it is no sharper than headroom× its on-screen footprint - the cap behind serializeCommands's maxImagePixelRatio (see render_command_codec.dart), extracted as a pure function so every branch is unit-testable without a giant fixture image.
colorantsToSrgb(PdfColorants v, Map<String, List<double>> spotEquivalents) PdfColor
Converts a colorant vector back to sRGB for display.
colorFromComponents(List<double> values, [int? count]) PdfColor
Interprets raw color components by count: 1 = gray, 3 = RGB, 4 = CMYK. Used for sc/scn operands and shading function outputs.
cropDownsamplePdfDecodedPixels(PdfDecodedPixels decoded, int sourceX, int sourceY, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight) PdfDecodedPixels?
Crops premultiplied decoded to the source rectangle and downsamples it to targetWidth×targetHeight. Returns null when the rectangle falls outside decoded. Shared by decodePdfImage's full-decode fallback and callers that already hold a decoded image to slice (a cached whole-image raster).
decodePdfImage(CosDocument cos, CosStream stream, {PdfImageRegion? region, int? targetWidth, int? targetHeight}) PdfDecodedPixels?
Decodes image XObject stream to premultiplied, codec-ready RGBA by stating what pixels you want, not which decoder can produce them:
decodePdfImageBase(CosDocument cos, CosStream stream) PdfImageBase?
Decodes the base image samples of stream to straight-alpha RGBA, WITHOUT applying any /SMask or stencil /Mask. Returns null for a non-CMYK DCTDecode base (needs the platform codec) or an undecodable image.
decodePdfImagePixels(CosDocument cos, CosStream stream) PdfDecodedPixels?
Decodes an image XObject stream to premultiplied, codec-ready RGBA purely (no dart:ui), or returns null when the platform JPEG codec is needed - a non-CMYK DCTDecode base, or any image paired with a DCTDecode- encoded /SMask - or the image can't be decoded. On null the caller falls back to the dart:ui decode path (decodePdfImageBase + the codec).
decodePdfImagePixelsRegionScaled(CosDocument cos, CosStream stream, int sourceX, int sourceY, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, {bool wholeImageOnlyIfDownscaled = false}) PdfDecodedPixels?
Decodes a rectangular source-region of a simple Flate/raw or CCITT image directly to targetWidth×targetHeight, or returns null when the stream needs the full general decoder.
decodePdfImagePixelsScaled(CosDocument cos, CosStream stream, int targetWidth, int targetHeight) PdfDecodedPixels?
Decodes a simple Flate/raw or CCITT image directly to targetWidth×targetHeight, or returns null when the stream needs the full general decoder.
decodeVectorPrint(Uint8List bytes) VectorPrintPage
Decodes a vector-print stream. Throws FormatException on a bad header or a truncated buffer.
decodeVectorPrintImagesPure(CosDocument cos, List<PdfImageRequest> requests) Future<Map<PdfImageRequest, PdfDecodedPixels>>
Pure-Dart image decode: everything decodePdfImagePixels can turn into RGBA without the platform codec. Undecodable images (a baseline JPEG needs dart:ui) are simply omitted, and the encoder skips drawing them.
deserializeCommands(Uint8List bytes) List<PdfRenderCommand>
Reconstructs the command buffer written by serializeCommands.
deserializePageText(Uint8List bytes) PdfPageText
Reconstructs the PdfPageText written by serializePageText.
downsamplePdfDecodedPixels(PdfDecodedPixels pixels, int targetWidth, int targetHeight) PdfDecodedPixels
Area-average (box filter) downsample of premultiplied RGBA pixels to targetWidth×targetHeight. Each destination pixel is the mean of the source pixels in its cell, so a large raster underlay shrinks to the resolution it is actually displayed at - the whole point on heavy CAD sheets, where a 160-megapixel scan blocks the raster thread (and blows the decoded-image cache) when drawn into a page only a few thousand pixels wide.
encodeVectorPrintPage(PdfPage page, {int? rotation, bool annotations = true, VectorPrintImageDecoder decodeImages = decodeVectorPrintImagesPure}) Future<Uint8List>
Interprets page and encodes it as a vector-print op stream (see the library doc for the model and decodeVectorPrint for the reader).
pdfApplyImageAlpha(Uint8List rgba, int width, int height, PdfImageSoftMask mask) → (Uint8List, int, int)
Bakes mask's alpha into rgba, returning the resulting (bytes, width, height). When the mask is HIGHER resolution than the base image - common for /Mask stencils where a tiny colour image carries a large crisp cutout (issue4246: a 50x40 gradient under a 1000x800 letter mask) - the result is built at the mask's resolution with the colour bilinearly upsampled, so the cutout's detail survives instead of being crushed to the base grid (which the device would then upscale into visible blocks). Otherwise the mask is point-sampled onto the base in place.
pdfApplyImageDecodeAndColorKey(Uint8List rgba, int components, List<(double, double)>? ranges, List<(int, int)>? colorKey) → void
Applies a /Decode lookup and color-key transparency to RGBA pixels in place. Keying compares the pre-/Decode samples (§8.9.6.4), so it runs before the lookup.
pdfBidiIsolateForCopy(String text) String
Adds Unicode direction metadata suitable for putting extracted text on a plain-text clipboard.
pdfDecodePageText(Uint8List bytes) PdfPageText?
Reverses pdfEncodePageText, or returns null when bytes are absent, truncated, corrupt, or from an incompatible format - every such case is a cache miss the caller recomputes from.
pdfEncodePageText(PdfPageText page) Uint8List
Serializes page into a compact binary blob for the on-disk text cache. The format is little-endian and self-describing enough to reject foreign/old bytes (pdfDecodePageText returns null on any mismatch). No external dependency - just dart:typed_data.
pdfImageColorants(CosDocument cos, CosStream stream, {CosDictionary? resources}) PdfImageColorants?
The colorant reading of image XObject stream, or null when it has none.
pdfImageColorFamily(CosDocument cos, CosDictionary dict) String
Maps the image's /ColorSpace to the device family used for decoding.
pdfImageColorKeyRanges(CosDocument cos, CosDictionary dict, int components) List<(int, int)>?
Color-key masking ranges (§8.9.6.4): /Mask as an array of min max pairs in raw sample space; samples inside every range go transparent.
pdfImageDctSoftMaskBytes(CosDocument cos, CosDictionary dict) Uint8List?
The DCTDecode-encoded /SMask's JPEG bytes (wrapping filters undone), or null when the /SMask is absent or not DCT. The dart:ui layer decodes these with the platform codec to recover the alpha plane.
pdfImageDecodeIgnoresTarget(CosDocument cos, CosStream stream) bool
A stream at one requested size. CosStream has no ==, so this keys by object identity - which is what we want: the same loaded stream object, not a re-read of the same bytes. Whether decoding stream at a reduced target size costs the same as decoding it whole - i.e. the decoder has no scaled fast path for it and falls back to a full decode plus downsamplePdfDecodedPixels.
pdfImageDecodeRanges(CosDocument cos, CosDictionary dict, int components) List<(double, double)>?
Per-component (min, max) pairs from /Decode, or null when absent or not matching components.
pdfImageFilters(CosDocument cos, CosDictionary dict) List<String>
The image's /Filter names in order (resolving the dict and array forms).
pdfImageOverprintStream(CosDocument cos, CosStream stream, {CosDictionary? resources, required PdfColorants backdrop, required PdfColor backdropColor, required int mode, required Map<String, List<double>> spotEquivalents}) → CosStream?
A substitute for image XObject stream whose samples are already composited over backdrop under overprint mode mode (§8.6.7), or null when no substitute can be built.
pdfImageSoftMask(CosDocument cos, CosDictionary dict) PdfImageSoftMask?
Decodes a non-DCT /SMask: a grayscale image whose samples become the alpha channel of its parent image (§11.6.5.2). Returns null when there is no /SMask, or it is DCT-encoded (use pdfImageDctSoftMaskBytes), or its shape is unsupported.
pdfImageStencilMask(CosDocument cos, CosDictionary dict) PdfImageSoftMask?
An explicit /Mask stencil stream (§8.9.6.3): 1-bit samples where 1 means "masked out" (transparent); /Decode 1 0 flips the polarity.
pdfPageRasterPixels(PdfRect box, double? ratio) int?
How many pixels a page whose media/crop box is box rasterizes into at ratio screen pixels per page point - serializeCommands's pageRasterPixels.
pdfPremultiplyRgba(Uint8List rgba) → void
Premultiplies straight-alpha RGBA in place. decodeImageFromPixels treats rgba8888 as premultiplied, so straight alpha would make transparent-but- colored pixels (a white backdrop under an /SMask cutout) composite additively as solid color.
replayCommands(List<PdfRenderCommand> commands, PdfDevice device, {int start = 0, int? end}) → void
Replays commands into device, reproducing the original interpreter callbacks in order. The dispatch is total over the PdfRenderCommand hierarchy - adding a command without a case here is a compile error.
replayCommandsCancellable(List<PdfRenderCommand> commands, PdfDevice device, {PdfCancellationToken? cancellation, int checkInterval = 1024}) Future<void>
replayCommands in cooperative chunks: every checkInterval commands it checks cancellation and yields to the event loop, so a message (e.g. a render worker's cancel port) can preempt a long replay mid-walk by throwing PdfCancelledException - the same scheme the interpreter's async walk uses. Soft-mask groups replay atomically inside their enclosing command.
serializeCommands(List<PdfRenderCommand> commands, {CosDocument? cos, bool decodeImages = false, double? maxImagePixelRatio, PdfRect? imageDecodeRegion, double imageBudgetFactor = _imageBudgetFactor, int? pageRasterPixels, bool imagePlaceholders = false, int? commandLimit, PdfImageDecodeCache? imageCache, bool compactStateScopes = false}) Uint8List?
serializePageText(PdfPageText page) Uint8List
Serializes an extracted PdfPageText for the render worker → UI-isolate hop (#396: off-thread text extraction). It is plain data - the page index, the page text, and each run's geometry - so it crosses the boundary as a compact byte buffer instead of a graph copy. The search quads/rects a match needs are recomputed from the runs on the UI isolate, so they are not serialized.
tokenizePageText(PdfPageText page) List<PdfTextToken>
Splits a page's extracted text into word tokens (maximal runs of non-whitespace) with their page-space bounds.

Typedefs

PdfImageDraw = ({PdfColor stencilColor, CosStream stream})
What an image draw resolves to once overprint has been applied: the stream the device should draw, and the colour a stencil paints through its mask (issue #604).
VectorPrintImageDecoder = Future<Map<PdfImageRequest, PdfDecodedPixels>> Function(CosDocument cos, List<PdfImageRequest> requests)
Decodes the RGBA pixels of the images a page references, keyed by request.

Exceptions / Errors

PdfCancelledException
Thrown when a PdfCancellationToken fires mid-walk.