Skip to content
go-pdfkitPublic

About

Pure-Go (CGO=0) PDF rasteriser: graphics state, paths, images, text and shadings, on go-gfx and go-opentype

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

135 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

render

CI Go Reference Go Report Card License: BSD-3-Clause Coverage

Turns a page of a PDF into pixels, in pure Go with no C anywhere.

It reads with reader, takes what a document says about its fonts from pdffont, rasterises with go-gfx/gfx, and — where there is text — shapes and outlines it with go-opentype. Nothing else: this builds for GOOS=js/wasm and every architecture the fleet targets, which is what lets a PDF be shown in a browser tab with nothing on the far end.

What it draws

The graphics half of the format: the transform stack, path construction and every one of the ten painting operators, filling under both winding rules, stroking with the caps, joins, miter limit and dash pattern the graphics state carries, clipping — including clips that intersect and are let go again with Q — the device, calibrated, profile-based, indexed, separation and pattern colour spaces, constant transparency, and form XObjects with their own matrix, bounding box and resources.

Images too: XObjects and inline images, at every bit depth the format has, in every colour space, with a /Decode array, as one-bit stencils painted in the colour in force, and with either kind of transparency — a soft mask of levels or a stencil of what to leave out. A format nothing here reads is left undrawn rather than drawn wrong.

Which decoder runs is part of what this draws, so it is named:

filter decoder
/DCTDecode go-images/jpeg — Go's own image/jpeg with one change, a four-component picture's chroma upsampled the way libjpeg does rather than by repeating each sample. The standard library merges those four planes itself and hands back an *image.CMYK, so a caller cannot put it right afterwards: the planes are gone. Worth 36 levels to 2 on the cyan plate of one corpus picture.
/JPXDecode go-images/jpeg2000, a fork for the same kind of reason
/JBIG2Decode go-gfx/gfx/codec, where the fleet keeps its image decoders
/CCITTFaxDecode, /FlateDecode, /LZWDecode, /RunLengthDecode go-pdfkit/reader, which runs them to samples

This said "a JPEG is decoded by the standard library", which stopped being true when the fork was taken.

Text: the whole text state and every positioning and showing operator, with glyphs taken from an embedded TrueType or OpenType font, from a PostScript Type 1 program, from a bare CFF one, from a composite font addressed by character identifier, or — for a Type 3 font, whose glyphs are little content streams — by running them. A simple font is addressed by the name its encoding gives a code, and falls back on the program's own built-in encoding when the document says nothing. A font whose program the file does not carry at all — two pages of the corpus in five — is drawn in a stand-in: Arimo, Tinos and Cousine are metric-compatible with Helvetica, Times and Courier, so the text comes out the width it was meant to be even where the document gives no widths of its own. A bold is made by stroking the outline as well as filling it and an italic by leaning it over, since only one weight of each stand-in is carried. Symbol and the dingbats are left alone: no face here has their glyphs, and something is not better than nothing when the something is the wrong alphabet.

Gradients and patterns: the axial and radial shadings that carry nearly every gradient anyone draws, painted on their own with sh or used as a fill or a stroke; tiling patterns, coloured and uncoloured, run once per cell and clipped to the shape; and the four kinds of function the format has — a sampled grid, an exponential curve, several of them stitched end to end, and a little PostScript program — which are also what a Separation or DeviceN colour space's tint transform is written in.

And the mesh shadings, all four of them, which is how a plotting tool writes a surface: free-form and lattice-form triangles, each corner its own colour, and Coons and tensor patches, whose four sides are curves. A patch is drawn by cutting it into a grid of little quadrilaterals — the inside of a Coons patch follows from its twelve boundary points, and a tensor patch says four more — and every triangle is filled by mixing the colours at its corners across it. A patch may carry on from the one before it, sharing an edge and two of its colours, which is how a surface is written without repeating a single point.

A pattern is placed in the space of the content that names it. That is the page's own space at the top level, and inside a form it is the form's: its matrix and the transform that drew it both count. Nearly every figure a plotting tool writes is a form, so a pattern that stayed at the page's origin would miss the shape it was asked to fill by the width of a page.

A page as SVG

err := render.PageSVG(doc, 1, w, render.SVGOptions{
	MaxBytes:    8 << 20,          // refuse (ErrSVGTooLarge), writing nothing; default 64 MiB
	RasterScale: 2,                // pixels per point of the embedded pictures; default 2
	MaxDuration: 5 * time.Second,  // as Options.MaxDuration; ErrTimedOut; default 10 s
})

Options.MaxDuration reads the clock by cost: after every 65 536 pixels drawn (fills, strokes, shadings, images) and every 256 operations, so a page of a few huge fills stops within about one fill of its budget.

On any error other than a failing writer nothing is written: the document is built in memory, bounded by MaxBytes, and handed to w in one call, so half a document never passes for a whole one.

Paths, clips, images, transparency groups and text (as outlines, so no font is needed) become SVG elements. What SVG 1.1 cannot say, which is tiling and shading patterns, shadings and soft masks, is drawn by the pixel renderer and embedded as an <image> where it falls. The document holds only numbers, generated ids and base64 data: nothing the PDF says is copied as text, href is #id or a data:image/png|jpeg;base64, URI, and there is no <script>, <foreignObject>, <style> or on* attribute. NaN and infinities are never printed. The allowlist is checked in production, not only in the tests: PageSVG reads the finished buffer once more, element by element and attribute by attribute, and refuses it (writing nothing) if anything is off it; that costs one allocation per id and none per byte. Every document the test suite draws is also held to it, and FuzzPageSVG does the same for any content stream.

A small file cannot ask for much. A picture is only as large as the clip it is drawn under, never the page; equal pictures are embedded once and used where they fall; a rectangle clip inside a rectangle clip is their intersection, one clip, and clips of any other shape may nest 64 deep (more is ErrSVGTooDeep); MaxDuration is ten seconds when left at zero. The test TestASmallFileCannotAskForMuchMemoryOrOutput states the measured bounds.

Limits, stated rather than hidden:

  • Text render modes 4 to 7 (clip) are not honoured, as in the pixel renderer (#137); blend modes are not either (#138).
  • Knockout groups are not read.
  • Images are smoothed by an SVG viewer where the raster path is nearest-neighbour; opaque JPEG-like images are re-encoded at quality 90.
  • A transparency group under a soft mask is embedded as a picture whose alpha is recovered from the painted-coverage grid, an approximation: the worst channel difference from the pixel renderer is 1 level in the test pages.
  • The independent check, oksvg, draws only shapes and text (no <image>, no clip paths, and it never reads fill-rule): on the five vector pages it can draw, the worst mean difference from the pixel renderer is 0.23 levels per channel, with 0.17 % of pixels far.

Thumbnails, and a strip of them

A page strip wants a hundred small pictures of somebody else's file, quickly and without being able to be made to allocate. That is Page with three options and nothing else:

img, err := render.Page(doc, i, render.Options{
    Scale:       0.2,              // device pixels per point: a 612pt page → 122px
    MaxPixels:   4 << 20,          // what the file may ask to allocate
    MaxDuration: 2 * time.Second,  // what it may ask to spend
})
rgba := img.ToNRGBA()              // for a toolkit that wants image.RGBA

Scale is the thumbnail control — device pixels per point, so 0.2 is a fifth of the page's own size. MaxPixels and MaxDuration are the two bounds a caller drawing an untrusted file needs: one caps what comes out, the other caps the work of making it. ⛔ On a timeout the page comes back as far as it got, with ErrTimedOut — deliberately not a blank, because half a page is worth more than nothing to somebody scrolling, and the error says plainly that it is half.

MaxBytes is the third bound: the most memory the page may hold at once beyond the image itself (clip grids, soft masks, a group's saved paper, decoded pictures, the path being built). Every such allocation is reserved before it is made and given back when its owner goes; a refused reservation ends the page at the next operation with ErrTooLarge, the image so far returned with it, as for ErrTimedOut. Zero means 256 MiB plus 16 bytes a pixel (about 400 MiB for A4 at 300 dpi). Decoder and rasteriser working storage is bounded by the input and the page, and is not counted. More than 256 q open at once are ignored, with the Q that closes each. A panic anywhere in drawing comes back as ErrInternal instead of leaving Page, PageSVG or Images; under GOOS=js a draw abandoned by MaxDuration cannot be stopped from outside, so there MaxBytes and MaxPixels are the bounds that hold.

Measured on a 68-page scanned book, at load average 25 so the figures are pessimistic:

scale per thumbnail worst page pixels in the strip
0.15 21.9 ms 54 ms 25 394
0.25 21.7 ms 93 ms 69 989
0.50 20.3 ms 31 ms 271 545

⛔ The scale barely moves it, and that is the useful part. Ten times the pixels cost the same, because on a scanned page the time goes into decoding the embedded image, not into rasterising it — so for scans, asking for a larger thumbnail is nearly free, and asking for a smaller one saves nothing. A strip of a hundred is about two seconds; a virtualised strip that draws only what is on screen is a tenth of that.

How it is checked

By writing a PDF whose geometry is known and looking at the pixels that come out: a rectangle from (10,10) to (40,40) on a hundred-point page has to be ink at (25,75) in the image and paper at (25,55), which is what says the page's coordinates — which count up from the bottom left — were mapped the right way up. Rotation, a media box that does not start at the origin, the crop box winning over the media box, every colour space, both winding rules, clipping, transparency and forms are all checked the same way.

Then on the corpus, for robustness rather than correctness: 4 108 pages drawn from 3 999 real files with no panics and no failures. 6 of them come out blank, which is the honest count of pages carrying nothing this wave understands yet — it was 373 before images, 31 before text, and 26 before Type 1 and bare CFF font programs.

And, when what is underneath changes, on the corpus again — by hashing every page's pixels before and after rather than by watching the exit status. That is how the two defects behind gfx v0.10.0 and opentype v0.7.0 were measured: a stroke assembled out of overlapping pieces came out at about half the colour it was asked for, and a CID font that carried no character map was refused outright, taking every glyph in it off the page. 3 520 of 4 057 pages changed; 1 705 of them gained ink, one of them twice over.

Testing

go test -covermode=set ./...

CI gates on exact 100% statement coverage, go vet, and a cross-compile across linux/{amd64,arm64,riscv64,loong64,ppc64le,s390x}, js/wasm, darwin/arm64 and windows/amd64.

and a cross-compile — it also RUNS the suite where it used only to build it. Eight lanes beyond linux/amd64:

lane how
riscv64, loong64, ppc64le, s390x, arm go test ./... under qemu-*-static
386 natively — qemu-i386 loses the guest's floating-point state across preemption, which failed five of eight runs and passed eight of eight with asyncpreemptoff=1; the workflow carries that measurement beside the lane
macos-latest, windows-latest go test ./... on the runner

s390x is big-endian. Cross-compiling for darwin and windows is not running there, and poppler and pdfium are tested on both — so those two are not new ground, they are ground the references hold and this repository did not: path handling, line endings and file semantics are where a Linux-only suite is quietly incomplete.

The rest of the family

reader reads and writes the format · ops is the verbs and the pdfops command · render turns a page into pixels · pdffont is what a document says about a font · extract reads a page back · coedit is a PDF several people edit at once · app is the browser workbench.

Documentation for all of it: https://go-pdfkit.github.io/docs/

License

BSD-3-Clause — see LICENSE. Copyright the go-pdfkit/render authors.

About

Pure-Go (CGO=0) PDF rasteriser: graphics state, paths, images, text and shadings, on go-gfx and go-opentype

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages