Skip to content

pdf

Mojo module 🡭

pdf

PdfCanvas: a DrawTarget that writes PDF documents.

Every call appends operators to the current page’s content stream, in the same coordinate space the other backends use: the stream opens with 1 0 0 -1 0 h cm, which flips PDF’s bottom-left, y-up page onto the canvas’s top-left, y-down pixels, so a caller’s numbers go through unchanged and one unit is one point (1/72 inch). new_page starts another page; a document is one page until it is called.

What maps onto PDF one to one: Path onto m/l/c/h (a quadratic is raised to a cubic, an arc_to becomes cubic arcs of at most a quarter turn each), the two fill rules onto f and f*, strokes onto w/J/j/M/d/S, the transform onto cm inside a q/Q pair around each element (as SvgCanvas writes a transform attribute per element, so no CTM state has to be tracked), a translucent color or a blend mode onto an ExtGState (/ca, /CA, /BM), a rectangle or path clip onto re W n / W n inside a q that pop_clip closes with Q, a linear or radial gradient onto an axial or radial shading (sh) with a stitching function over the stops, clipped to the shape, and a Canvas drawn with draw_image onto an image XObject with a soft mask for its alpha.

draw_text lays text out as the raster backend does and writes each run of glyphs as a TJ in the font that produced it, the font embedded as a subset (canvas.vector.pdf_font) with a ToUnicode map, so a label is selectable, searchable and copyable. A fallback font a glyph came from is embedded alongside the primary. The content stream and the font programs are Flate-compressed through this package’s own deflate.

Unsupported features are Porter-Duff operators other than source-over, alpha on gradient stops, conic gradients, ColorSpace.LINEAR, and color bitmap glyphs. Unsupported blend operators render source-over; the other unsupported features are omitted or ignored. Annotated groups become marked content (/Span << /Alt (title) >> BDC ... EMC), which is what a PDF has for “this run of drawing has a label”.

Structs

  • PdfCanvas: A PDF document built from DrawTarget calls, one page at a time; see the module docstring for what each becomes. to_bytes produces the file, write_pdf writes it.

Functions