ops

package module
v0.45.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: BSD-3-Clause Imports: 34 Imported by: 4 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ops

CI Go Reference Go Report Card Coverage

The verbs of go-pdfkit: what people actually do to a PDF they already have. Merge two files, pull out pages three to seven, turn a page the right way up, drop the metadata, split a report into chapters.

Built on reader, which takes a file apart and puts one back together; nothing outside the Go standard library is used, so this builds for GOOS=js/wasm and every architecture the fleet targets.

The model

A document here is an ordered list of pages, each borrowed from a source file, plus the document-level pieces. Every operation rearranges that list or annotates its entries; nothing is applied until the document is written out. An operation therefore costs nothing until it has to, several files can be mixed freely, and — the reason the model is shaped this way — the list is a plain value that two people can edit at the same time.

What it does

go install github.com/go-pdfkit/ops/cmd/pdfops@latest

pdfops merge whole.pdf part1.pdf part2.pdf
pdfops select -pages 3-7,last report.pdf extract.pdf
pdfops delete -pages even scan.pdf fronts.pdf
pdfops rotate -pages all -by 90 sideways.pdf upright.pdf
pdfops turn -by 30 tilted.pdf turned.pdf
pdfops compare draft1.pdf draft2.pdf
pdfops crop -box 20,20,575,820 wide.pdf trimmed.pdf
pdfops resize -to a4 odd-sizes.pdf a4.pdf
pdfops resize -to a4 -landscape slides.pdf wide.pdf
pdfops move -from 1 -to 3 misplaced.pdf ordered.pdf
pdfops split -every 10 book.pdf chapters/
pdfops reverse back-to-front.pdf right-way-round.pdf
pdfops nup -n 4 slides.pdf handout.pdf
pdfops booklet chapter.pdf to-fold.pdf
pdfops interleave both.pdf fronts.pdf backs.pdf
pdfops duplex scan.pdf document.pdf
pdfops onepage strip.pdf one-long-page.pdf
pdfops poster -across 2 -down 2 plan.pdf tiles.pdf
pdfops divide -across 2 spread.pdf pages.pdf
pdfops overlay -with letterhead.pdf plain.pdf headed.pdf
pdfops underlay -with watermark.pdf report.pdf behind.pdf
pdfops blank -before 3 report.pdf report-with-a-gap.pdf
pdfops watermark -text CONFIDENTIAL contract.pdf marked.pdf
pdfops number -format "{page} of {pages}" report.pdf numbered.pdf
pdfops bates -prefix ACME- -start 1 exhibits.pdf stamped.pdf
pdfops stamp -text "seen 25 August" -at top-right -bold notes.pdf seen.pdf
pdfops place -image signature.png -at bottom-right -width 120 contract.pdf signed.pdf
pdfops place -image logo.png -x 40 -y 740 -dpi 300 -opacity 0.3 plain.pdf headed.pdf
pdfops sanitize downloaded.pdf safe.pdf
pdfops flatten filled-form.pdf final.pdf
pdfops strip -annotations -bookmarks private.pdf clean.pdf
pdfops compress fat.pdf lean.pdf
pdfops encrypt -user letmein -allow print,copy plain.pdf locked.pdf
pdfops -password letmein decrypt locked.pdf plain.pdf
pdfops -password letmein permissions locked.pdf
pdfops text paper.pdf
pdfops text -layout -pages 1 paper.pdf
pdfops text -layout -json paper.pdf
pdfops tables accounts.pdf
pdfops tables -as md -pages 3 accounts.pdf
pdfops tables -as json -to tables/ accounts.pdf
pdfops markdown report.pdf > report.md
pdfops markdown -json report.pdf > report-for-indexing.json
pdfops word report.pdf report.docx
pdfops excel accounts.pdf accounts.xlsx
pdfops objects broken.pdf | jq .
pdfops images paper.pdf pictures/
pdfops links report.pdf
pdfops links -pages 1-3 report.pdf
pdfops attachments report.pdf
pdfops attachments -to files/ report.pdf
pdfops attach -file figures.csv -description "the figures" report.pdf with.pdf
pdfops detach -name figures.csv with.pdf without.pdf
pdfops outline -from toc.txt book.pdf bookmarked.pdf
pdfops outline -drop bookmarked.pdf plain.pdf
pdfops contents -from toc.txt -bookmarks book.pdf with-contents.pdf
pdfops info file.pdf
pdfops metadata -set 'Title=The Report' -set Author=Someone draft.pdf titled.pdf
pdfops metadata -clear draft.pdf anonymous.pdf
pdfops version -set 1.7 old.pdf declared.pdf

A page range is written 1-3,7,10- and may say all, even, odd or last. It keeps its own order and its own repeats, so select -pages 3-1 reverses three pages and select -pages 1,1 gives you two copies.

-password opens an encrypted file.

links lists what the document's pages link to — a page of the same document, or an address — with the rectangle each link occupies, in the document's own page numbering. Reorder the pages or drop one and the list says where the links lead now, not where they led in the file they came from.

1    72,648,232,660    page 14
1    72,600,180,612    https://example.org/
3    90,120,300,132    nowhere

(the columns are tab-separated)

⛔ A link that leads nowhere this can follow is listed, and says so. It is a link all the same: a page the document no longer has, a jump into another file, a destination name nothing defines, or an action that runs something instead of going somewhere. Printing only the ones that work would answer "eleven" about a file holding twelve, and a listing that under-reports is worse than none — whoever is auditing a document for what it points at would never learn that the twelfth exists.

⛔ /A is read before /Dest. The link-annotation clause (ISO 32000-1 §12.5.6.5, Table 173) does not permit /Dest beside an /A, so a file carrying both is malformed — and the action is what a reader acts on, so it is what this reports. A rectangle written from either pair of corners is normalised, because a caller hit-testing a back-to-front one finds nothing at all, which looks exactly like a page with no links on it.

interleave takes one page from each file in turn, which is how two single-sided scans — the fronts and the backs — become one double-sided document. onepage stacks every page onto a single long one. poster cuts each page into tiles so a plan can be printed larger than the paper and assembled.

deblank finds the pages that hold nothing and drops them. It draws each page and counts the pixels that are not paper, because that is the only test that agrees with a reader: a page whose content stream is full of operators painting white, or drawing outside the media box, looks blank and is blank, and a page carrying a picture of nothing is blank too.

pdfops deblank -list scan.pdf          # say which, write nothing
pdfops deblank scan.pdf tidied.pdf

⛔ The default resolution is 150 DPI, and it was raised from 50 because of a measurement. On A4:

50 DPI 150 DPI
the page 414 × 585 1240 × 1755
one pixel 4.1e-06 of it 4.6e-07
an 8-point full stop 1 pixel 4 pixels
an 8-point comma 2 pixels 8 pixels

At 50 DPI a full stop is exactly the mark a speck of dust makes, so no threshold at that resolution can tell punctuation from dirt. At 150 there is a factor of four to set -max-ink from, and TestMeasureTheInkLadder prints the whole ladder so that a renderer change which moved either end fails there instead of silently reclassifying somebody's pages.

⛔ The zero value is the strictest setting, not a middle one: a page with a single inked pixel is kept. This is the input to deleting pages — a page wrongly called blank destroys content, while a blank page wrongly kept merely leaves a blank page. For scans, -max-ink 1e-6 is about two pixels: it forgives a speck and still keeps a page holding a full stop. It is not the default because whether that margin holds depends on the scanner, which this package cannot see.

Three more things it will not do:

  • it will not call a page of solid colour blank. The test is distance from white, not uniformity; a measure of variance would delete a deliberate black separator sheet;
  • it will not empty the document. Every page blank is an error, because a file of no pages still opens and still has a size, and a caller handed one would be told nothing was wrong;
  • it does not count annotations as ink unless asked: a page whose only mark is a sticky note is blank paper somebody wrote on.

And -list writes nothing and takes no output file, because the first thing anybody should do with a tool that deletes pages is ask it which ones it means.

deskew straightens the tilted pages of a scan. It draws each page to measure it, and reports every page's angle and whether it was turned.

pdfops deskew -list scan.pdf              # just the angles, write nothing
pdfops deskew scan.pdf straight.pdf
pdfops deskew -threshold 0.1 -dpi 300 scan.pdf straight.pdf

The angle comes from Baird's projection profile (The skew angle of printed documents, Proc. SPSE 1987): the page is sheared rather than rotated — which keeps the scan-line counts exact, where resampling would blur the very line structure being measured — and the angle taken is the one that maximises the variance of the marked-pixel count per scan line. The survey that compares the methods (Mascaro, Cavalcanti et al., Pattern Recognition Letters 31 (2010) 1403–1411) ranks it first on documents with clear separation between text lines, which is what a page of text is.

⛔ The correction is not a rasterisation. The angle is measured on a render, but it is applied as a transformation of the page's own content, so text stays text and a vector drawing stays vector. A deskew that flattened the page would quietly undo the thing a scan is usually deskewed for, which is OCR.

Judged by tesseract, which knows nothing of this code: a rendered page it reads at 0.968 similarity straight, and at 0.895 tilted by 7°, it reads back at 0.968 once deskewed — the straight page's own figure.

A page under -threshold is reported and left alone, byte for byte: a scan that is already level should not come back rewritten. A page with nothing on it has no skew, and is reported as such rather than counted as level — one blank separator sheet does not stop the other three hundred being straightened.

⛔ -dpi is a measurement setting only, since nothing of the render reaches the output: a higher value buys accuracy and costs time, and never quality. Too low a value does silent damage, though — the projection has to resolve the text lines, and below about two samples per line pitch it returns an angle that is simply wrong. See SkewOptions.MaxPixels in go-images for the measured table.

turn turns pages by any angle, which is the half rotate refuses: rotate writes a number on the page — /Rotate, a multiple of ninety — and turn rewrites the page onto a sheet of its own.

pdfops turn -by 30 tilted.pdf straight.pdf
pdfops turn -pages 2,5-7 -by -1.5 scan.pdf nudged.pdf

⛔ The paper grows and nothing is cut off, which is the whole difference from deskew. A deskew is a correction of a fraction of a degree on a page whose text sits well inside its margins, so it keeps the paper it was given; a turn by thirty degrees would lose two corners if the paper did not grow with it. The sheet is the turned page's bounding box — w·|cos θ| + h·|sin θ| across, w·|sin θ| + h·|cos θ| down — and the page is centred on it, which the tests check by mapping all four corners for angles from −350° to 350°: each must land inside the sheet, and each edge must be touched, or the box is bigger than it needs to be.

An angle that is a multiple of ninety goes through /Rotate and nothing else happens: no transformation, no new content stream, and a page whose text was selectable stays selectable.

⛔ Positive is clockwise, and the reference this is ported from contradicts itself about that. BentoPDF's rotate-custom documents "Positive values rotate clockwise"; its code writes a multiple of ninety as /Rotate — which ISO 32000-1 Table 30 defines as degrees clockwise — and sends every other angle through pdf-lib's drawPage, which concatenates [cos sin −sin cos], a counter-clockwise turn in a space whose y counts upwards. The two arms turn opposite ways and the seam is at exactly 90°. Here both are clockwise, and the gate is a render: a mark at the top of a square page must come back at the right-hand edge after +90°, the way a clock's hand goes from twelve to three — measured at 89°, 90° and 91° so that the seam itself is crossed.

compare says what changed between two versions of a document.

pdfops compare draft1.pdf draft2.pdf
- -> 2    page added
2 -> 3    text removed       zeta
2 -> 3    text added         theta
2 of 3 page(s) changed

⛔ The pages are paired by what they say, not by their numbers. A page inserted in the middle moves nothing after it: the pages that follow are still paired with the pages they came from, and the insertion is one page added. Pairing by number would report that page as an edit of the next, that one as an edit of the one after, and so on to the end — every page of the document changed, which is both useless and false.

A pair has to share half its words, or it is one page removed and another added. Without that floor the alignment pairs the least unalike pages it can find, so a replaced chapter reads as a rewrite of the one before it.

Inside a pair the diff is Myers (An O(ND) Difference Algorithm and Its Variations, Algorithmica 1 (1986) 251–266), over words, and the words that changed together are reported together: "quick brown fox" → "slow grey mole" is two changes and not six. Pictures are told apart by a hash of their samples, so a swapped logo of the same size is a change; annotations by their subtype and their text.

⛔ compare exits 0 whether or not the documents differ, unlike diff: in this command an exit of 1 means the work could not be done, and a document that changed is the work being done. The answer is in the last line, in words.

⛔ divide makes the same grid as poster and is the opposite operation. poster keeps every piece the size of the page it came from, so it enlarges: the pieces taped together make one page the size of a wall. divide keeps the content at its own size and makes the pages smaller, so the pieces laid side by side are the page again at 1:1 — which is what a two-page spread scanned as one wide sheet, or two tickets printed on one page, needs.

Confusing them gives a result that looks right in a thumbnail and is wrong by a factor of across and down. The tests assert the media box, not the page count, and TestDivideIsNotPoster compares the two directly: without it, every assertion about divide could be satisfied by poster.

duplex is the same job when the scanner left one file rather than two: a feeder that cannot turn a sheet over gives every front, then every back. It cuts the file in the middle and interleaves the halves.

⛔ The backs are reversed by default, and the flag is -keep-backs rather than -reverse-backs so that the default is the common case: the stack is turned over as a stack, so the last sheet's back is scanned first. A tool whose default assumed otherwise would quietly put every back on the wrong front — which reads as "the scan is fine, the order is odd" rather than as a reversal.

The default split is ceil(n/2), not n/2: an odd stack has its unpaired sheet at the end of the fronts, so thirteen pages split at seven. ⛔ The test for that had to be rewritten. The first version used a reversed back block — and with the backs reversed the output is the same for any split in a range, because the reversal absorbs the difference. It passed at the ceiling and at the floor, so it proved nothing; the negative control is what said so, and the assertion now uses -keep-backs, where the split is load-bearing.

place draws a picture where you say it goes: a scanned or typed signature, a logo, a seal. It is stamp with an image instead of a line of text, and it deliberately takes the same words for where — the nine positions and a margin — so that -at bottom-right means the same thing for both.

pdfops place -image signature.png -at bottom-right -width 120 contract.pdf signed.pdf
pdfops place -image logo.png -pages 1 -x 40 -y 740 -dpi 300 plain.pdf headed.pdf
pdfops place -image seal.png -at center -opacity 0.3 draft.pdf sealed.pdf

Three ways of saying how big, and they are tried in that order: -width or -height alone keeps the picture's proportions (a signature scaled into a box is a signature nobody recognises), both together may distort it, and neither falls back to -dpi — the picture's own pixels, where 300 means a 300-pixel-wide picture is an inch across. The default is 72, one point per pixel.

⛔ A picture above 40 megapixels is refused, and the ceiling is yours to move. The size a picture declares comes from the file, and a compressed format describes a huge image in a few bytes — a PNG saying 100000 by 100000 is tens of kilobytes that become tens of gigabytes — so go-gfx/gfx v0.37.0 reads the header first and refuses what is over codec.DefaultMaxPixels (40 million) before allocating anything. A 50 MP camera photo is therefore refused by default, with an error wrapping codec.ErrTooLarge. In Go, (*Doc).SetMaxPixels(n) sets the ceiling for Doc.Picture and Doc.Place (width times height; zero means the default, and a picture exactly at the ceiling is accepted); on the command line pdfops place -max-pixels 60000000 …. Raise it for photographs you trust; lower it to what you need for files from strangers.

⛔ -x -y is an anchor, not a hint: it is taken as given and not clamped into the page, and -at is then ignored rather than combined with it. A signature deliberately bleeding off the edge of a scanned form is a real request, and a viewer clips what falls outside the media box perfectly well. The nine positions clamp; an explicit corner is an instruction.

⛔ This is what "sign a PDF" means in every tool that offers it — a picture of a signature, placed. It is not cryptography, and nothing here pretends it is: a drawn squiggle proves nothing about who drew it. The cryptographic kind is a different job under a different name, and conflating the two is how a scanned squiggle comes to be called a digital signature.

⛔ The drawing itself was already here, and nothing could ask for it. The machinery that puts an image at a rectangle on a page was written for the XFA renderer, and only XFA fed it: the capability was present, tested through one caller, and absent from the outside. Worse, a borrowed page did not honour it at all, because the conditions deciding whether a source page is wrapped or cached counted marks and not pictures. Wiring it up found a second defect of the same shape in nup: a blank page that carries anything emitted an empty form, because the switch asked "is it blank" before it asked "is anything on it" — so blank then number then nup dropped the page numbers off the sheet, silently, and had always done.

repair writes a file back out with its structure rebuilt, and says whether rebuilding was needed. -check answers that question and writes nothing.

pdfops repair -check suspect.pdf
pdfops repair broken.pdf fixed.pdf

⛔ The rebuilding is not this verb's doing. go-pdfkit/reader repairs a damaged file on its own and quietly, which is the right behaviour for a reader — a caller asking for page three wants page three, not a lecture. What was missing was a way to say it happened and to keep the result, and that is the whole of this verb. Doc.Repaired() is the same answer in Go.

It reports on any source, not all: a merged document's pages come from several files, and one damaged source is the answer to "did this need repairing". A true that depended on every source being broken would be false for every real merge.

⛔ And the scope is reader's, not QPDF's. What it recovers is a cross-reference table that is wrong, missing, or points into the middle of something else — the commonest damage, and the kind where the objects are all still there. It is not a general salvage engine, and a file whose objects are themselves truncated may still be unreadable. A file that did not need repairing is said out loud and is not an error, so that "repair everything in this directory" can be scripted.

labels sets what a viewer shows in its toolbar — "iv of 320" — which is never what is printed on the paper. For a number on the page, that is number above.

pdfops labels -list book.pdf
pdfops labels -rule 'pages=1-12;style=r' -rule 'pages=13-;style=D' book.pdf out.pdf
pdfops labels -rule 'pages=all;style=D;prefix=A-;start=1' appendix.pdf out.pdf
pdfops labels -clear book.pdf plain.pdf

The six styles are the format's own: D (1, 2, 3), r (i, ii, iii), R (I, II, III), a (a, b, c), A (A, B, C), and an empty style, which is the prefix alone — how a run of pages is marked "Cover" or "Insert".

⛔ A page-label range in a PDF is CONTIGUOUS. The file holds the first page of each run and the viewer counts forward from there, so a rule over 1-9,30-40 has to be compiled into two runs. Without continue the second run starts again at start; with it, it carries on. pages=odd is the extreme of the same thing — fifty runs of one page over a hundred — and both answers are expressible only because a rule is compiled rather than stored as written.

⛔ A page-label tree has no gaps either. An entry labels from its own key until the next entry, so a document labelled 1, 2 and then meant to stop comes back 1, 2, 3, 4 unless the stop is said out loud: an entry with neither a style nor a prefix. The first draft skipped unlabelled pages and the round-trip caught it.

⛔ start must be at least 1, and that is the format's rule rather than a choice here: ISO 32000-1 table 159 says /St "shall be greater than or equal to 1". A zero-based numbering scheme is not expressible as a numeric style, so a start below one is refused rather than written out of specification — a file that opens in one viewer and renumbers itself in another is worse than a refusal. BentoPDF's own tool offers "set to 0 for zero-based numbering", and what that writes is a value the standard forbids.

⛔ A page label's letters are not a spreadsheet's columns. Table 159 says the letters run "A to Z for the first 26 pages, AA to ZZ for the next 26" — so 27 is AA and 28 is BB, where a spreadsheet's 28 is AB. Borrowing the spreadsheet rule, which is the one everybody has written before, relabels every appendix past the twenty-sixth.

Roman numerals stop at 3999, where the additive notation runs out — 4000 needs a bar over the M, which neither a PDF string nor a page number has — and past it the number is written in decimal. A label a viewer shows wrongly is worse than one it shows in the wrong style.

⛔ Every verb used to drop the page labels

A /PageLabels tree is keyed by page index, so it cannot be carried across a rebuild the way the other document keys are: after a select or a reverse every label would be on the wrong page. So this package dropped it — and a document whose front matter was numbered i, ii, iii came back from a watermark numbered 1, 2, 3.

The labels are now asked for per page and rebuilt, which is right in both directions: a verb that keeps the pages keeps their labels, and a verb that moves them moves the labels with them. A merge keeps each source's labels on its own pages.

The runs are compressed on the way out: three hundred decimal pages are one entry, not three hundred. A label no style can explain becomes a run of one with the whole label as a literal prefix — the file then says exactly what the viewer must show, at the cost of an entry.

layers is the optional content a viewer calls layers: a drawing's dimensions, its markup, its alternatives.

pdfops layers -list plan.pdf
pdfops layers -hide 'Internal pricing' plan.pdf out.pdf
pdfops layers -add 'Markup/Mine' plan.pdf out.pdf

⛔ Every verb used to lose them. Measured before this: a one-page drawing with a layer switched off, run through pdfops watermark, came back with no /OCProperties at all — the content still marked as belonging to a layer, the layer object still reachable through the page's own resources, and nothing left saying which layer was hidden. So the hidden layer showed. A drawing distributed with an "internal pricing" layer turned off revealed it to any verb at all.

The layers are now constructed on the way out rather than carried, which is what lets them survive a reorder and a merge: keepCatalogue refuses to merge two catalogues, because two forms whose fields are named the same cannot honestly become one — but two drawings' layers can, since a layer is its object and two layers named "Markup" are two layers.

What the file says about its own layers, and is obeyed
/BaseState OFF inverts the question: everything is hidden unless /ON names it. A reader that only looked at /OFF would report every layer of such a document as visible — and a drawing that ships with all its layers off but one is exactly how an alternatives document is built
/Locked the document asking that a layer not be switched. -hide on one is refused: a drawing's dimension layer is what everything else is positioned against, and switching it anyway ignores the only thing the file says
/D /Order the nesting, which is written back nested. A string inside it is the group's label rather than a layer

⛔ Dropping a hidden layer is refused, because what was drawn on it does not go with it: the content stays in the page and stops being optional, so the hidden drawing becomes permanently visible — the opposite of what somebody deleting a layer called "internal pricing" expects. Show it first if that is what you mean.

⛔ A name is not an identifier. A drawing assembled from two others often has two "Markup" layers, and switching one of them at random is a change nobody asked for and nobody can see, so an ambiguous name is refused with the count.

tables finds the grids a page's text lines up into, and writes them as CSV (RFC 4180, a blank line between one table and the next), as JSON (with the page and the box, so a caller knows where to look), or as GFM pipe tables.

pdfops tables accounts.pdf
pdfops tables -as md -pages 3 accounts.pdf
pdfops tables -as json -to tables/ accounts.pdf

A page holds no table — it holds text put at places — so this reports an inference, and extract is where the rules are: a boundary is a stretch every row leaves empty, a repeated one-character cell is a bullet and not a column, and a line far below the last row is not the next one. Ruled lines are not read, so a table held apart by rules rather than by whitespace is not found.

⛔ A page that could not be read is said on the error stream, not left to look like a page with no tables on it — and on the error stream rather than standard output, so that it cannot end up inside the rows somebody is about to parse.

⛔ The first row becomes the Markdown header. A pipe table has nowhere to put a table with no header row, and a grid found by looking at alignment does not know whether its first row is one. The cells go through go-richdoc rather than through a strings.Join here, so a cell holding a | is escaped by the code that already knew it had to be.

⛔ A document may say a word sits 10^308 points along, and a table with one word at minus that and another at plus it is infinitely wide. JSON has no spelling for an infinity, so -as json fails on such a file rather than writing "width": +Inf into something that has already begun parsing it.

markdown reads the pages back as a document — headings, paragraphs, lists and tables — through go-pdfkit/document, and writes them as Markdown. With -json it writes one record per page instead, each the page's Markdown plus the document's own metadata, which is the shape a retrieval pipeline already expects.

pdfops markdown report.pdf > report.md
pdfops markdown -pages 3-7 report.pdf
pdfops markdown -json report.pdf > report-for-indexing.json

⛔ A PDF has no headings. What this writes is an inference from how big the glyphs were and where they sat, and document's README says what it will and will not see — a page in columns, or a table held apart by ruled lines, is not read as either.

⛔ A page range is applied after the document is read, never before. What counts as a heading is decided by the sizes the whole document uses, so asking for page nine alone would otherwise give it different headings from asking for all of them — and a caller doing a document a page at a time would get a different answer for every page. A test asserts that page one reads the same both ways.

⛔ -json decodes the metadata. A title written in UTF-16 behind a byte order mark — which is most of what a modern producer writes — came out of the old code as \xfe\xffL\x00a\x00…. info printed it that way too, for as long as the verb had existed; both now go through reader.TextString.

word and excel write that same reading out as a .docx or an .xlsx, through go-ooxml.

pdfops word report.pdf report.docx
pdfops excel accounts.pdf accounts.xlsx

⛔ What comes out is the document, not the pages. The fonts, the margins, the line breaks and the page breaks are the typesetter's work; a .docx that reproduced them would be a picture of a PDF rather than something anybody can edit.

⛔ excel writes only the tables, one sheet each. A spreadsheet is a grid of cells and a document is not, so the prose around a table has nowhere to go — and a page with no tables gives the one empty sheet a workbook has to have rather than an error.

Both are the same function with a different writer, which is why -pages means the same thing in each and a defect found in one is fixed in both.

objects writes the object graph as JSON: what the file is made of, as opposed to what it says. For looking at a file that will not open anywhere else.

pdfops objects broken.pdf | jq '.objects["12 0"]'

⛔ It is the graph reachable from the trailer, not every object in the file. That is the honest set because it is the one a reader sees: an object no reference points at is in the bytes and in nobody's document.

⛔ A stream's bytes are not in it, its length and its dictionary are. They are the bulk of most files and they are binary, so including them would mean base64 — a 35 MB file becoming a 47 MB JSON nobody reads.

A name keeps its slash ("/Catalog") and a string is wrapped ({"text": "…"} or {"hex": "…"} where it is not text), because the two have to be told apart and a PDF string may be exactly /Catalog. A reference that could not be read is named in unread rather than dropped: "the graph, and these edges lead nowhere" is what somebody debugging a damaged file needs.

textcolour paints the text one colour and leaves the rest of the page alone.

pdfops textcolour -to '#0000ff' report.pdf blue-text.pdf
pdfops textcolour -to black -pages 1-4 scan.pdf fixed.pdf

⛔ Setting a colour before each text object is not enough, and that is what the first draft did. A text object that sets its own colour overrides it, so a page whose paragraphs say 1 0 0 rg came out unchanged while the tool reported success. Every colour operator inside a text object is blanked — g, rg, k, cs, sc, scn and their stroking capitals — so the colour asked for is the one that paints.

⛔ The colour goes outside the text object, wrapped in q/Q. A text object does not save the graphics state, so a colour set inside one leaks into whatever is drawn after it — which is how a recolouring turns a company's logo the same shade as its paragraphs. A test asserts the rectangle beside the text keeps its own red.

ocrtext makes a scan searchable. It draws a recogniser's words over the page in text rendering mode 3, which paints nothing, so the page looks exactly as it did and a viewer can find, select and copy the text. Library: Doc.AddInvisibleText(page, []Word{{Text, Box, Angle}}).

pdfops ocrtext -words words.json scan.pdf searchable.pdf
pdfops ocrtext -hocr page.hocr -page 3 scan.pdf searchable.pdf

words.json is {"pages":[{"page":1,"words":[{"text":"word","box":[left, bottom,right,top],"angle":0}]}]} (boxes in points, origin at the bottom left), or a bare array of words for the page -page names. -hocr reads what tesseract page.png out hocr writes: pixel boxes from the top left, scaled onto the page, with the baseline slope of each line as the angle.

The design is Tesseract's (src/api/pdfrenderer.cpp, "GlyphLessFont"): one Type0/CIDFontType2 font for the whole file, holding one empty glyph; a CIDToGIDMap that sends every code to glyph 1, never 0 (Acrobat refuses a font whose only reachable glyph is .notdef); Identity-H; and a ToUnicode CMap. Each word is placed by a text matrix and squeezed or stretched to its box by Tz, so no per-language font exists. Text is in logical order, so right-to-left words search and copy correctly; a character beyond the Basic Multilingual Plane takes one code whose ToUnicode entry is the surrogate pair. The page's own content is carried over untouched, wrapped in q/Q. Measured: a page of five hundred words is written in about four milliseconds.

⛔ Checked against other readers, not just this one: the words read back in order through this package's extraction and through poppler's pdftotext (which reorders right-to-left lines for display), the page renders to the same pixels, and qpdf --check and mutool accept the file. Limits, stated: the call refuses a page that is also redacted (the words would give back what the redaction took out), a page that was made rather than read, at most 100 000 words a page and 4 096 characters a word, and any coordinate that is not finite or is beyond 10 million points. Apply it last: a page tiled onto another afterwards (nup, poster, divide) is drawn from its own content and loses the words.

outlinetext writes the text as vector paths, so no font is left in the page (the "font to outline" step a printer asks for). Library: Doc.OutlineText.

pdfops outlinetext report.pdf outlined.pdf
pdfops outlinetext -pages 1-4 report.pdf outlined.pdf

Glyph outlines come from the font program (TrueType, CFF, Type 1, the standard 14) or, for a Type 3 font, from the glyph's own procedure, drawn as a Form XObject. Spacing, TJ, rise, horizontal scale and the clip render modes are kept; a page measured before and after differs by at most 0.002 % of its pixels. Text inside a Form XObject or tiling pattern is outlined in a copy, so a shared form is never changed under another page.

Limits, stated rather than hidden: vertical writing is refused; embolden (mode 2 on a stroked-only font) is ignored; annotation appearance streams are not reached and are counted (pdfops prints how many); text state a form inherits from the page is not followed; a page cannot be outlined and recoloured, redacted or text-edited in the same pass. The work is bounded (glyph count, output bytes, form nesting, q depth, marked-content depth, the size of a resource dictionary) and a bound refuses, never truncates: Bytes returns ErrOutlineTooLarge (or ErrOutlineVertical) and writes nothing.

⛔ Outlined text is no longer searchable, and neither are its descriptions. Marked content that gives text in words in place of what is drawn (/ActualText, /Alt, /E) would let a reader select and search the very words that were turned into shapes, so on an outlined page those entries are removed from the marked-content property lists, whether they are written inline or held as objects, and from the structure elements whose content is on such a page (an element with no page, and nothing in it, goes when any page is outlined). Everything that is not words (/MCID, /Lang, the structure itself) stays, so a tagged document stays tagged.

Text that outlining does not reach is counted, not hidden: pdfops prints how many annotations still hold text (a nested form, a FreeText or any annotation's /Contents, a form field's value, including one inherited from its parent field), and Doc.OutlineSkipped returns the number.

Both the filling and the stroking colour are set, because text has render modes: 0 fills, 1 strokes, 2 does both.

⛔ It splices, and does not re-serialise. Writing the operations back out would mean formatting every operand again, including an inline image's still-encoded bytes, where a formatter that is merely lossless-for-objects can change what the image means. So the rewriting keeps every byte it does not deliberately change — which is why reader.Operation carries its byte range, added for this. A stream with no text comes back byte for byte unchanged, and the colour operators are blanked with spaces rather than deleted so that every offset after one is still the offset the scan reported.

⛔ What it cannot reach, it counts. Text drawn through a Form XObject is not recoloured, and the reason is not difficulty: an XObject is shared, so recolouring one would change pages the caller did not name. A document whose text is all inside XObjects would otherwise come back looking converted and be unchanged — the one failure a caller cannot see by opening the result and glancing at it. So the count is said out loud, and Doc.UnreachedText is the same answer in Go.

And #f00 is full red: each digit of a short hex colour is doubled, not shifted, so the component is 0xf × 17. A shift gives 240/255 for what every browser calls full red, and a logo recoloured to 94 % red is a defect nobody can see but a printer.

attachments lists the files a document carries, and writes them out with -to. A name comes out of the document rather than from whoever runs the command, so it is stripped to its last element: ../escaped.txt is written inside the directory asked for, and a name with no usable last element is refused rather than skipped. detach refuses a name the file does not carry, instead of writing an unchanged copy somebody then sends believing it was removed.

outline replaces the bookmarks from a file, or removes them with -drop. The file is one bookmark a line — a title, a tab, a page number — with two spaces of indent for each level of nesting:

Introduction	1
  Why	2
Chapter one	7

A line it cannot read is an error naming the line, because a table of contents quietly missing an entry is worse than one that refuses to be written.

That grammar is ops.ParseOutline(text string) ([]Bookmark, error), in the library rather than in the command, so that anything else asked to write a table of contents — the browser workbench among them — accepts exactly the same file instead of carrying a second parser for it.

contents writes the same file as a printed table of contents — a page of the document, each line a title at the left, its page number at the right and dots leading to it:

Contents

Introduction ....................................... 2
  Why .............................................. 3
Chapter one ........................................ 8

⛔ The numbers it prints are moved by the pages it adds. A contents page put in front of a document pushes every page of it down, so an entry that pointed at page 7 is on page 8 afterwards, and printing the 7 would send a reader one page short of every heading in the book. ops.ContentsPage returns how many pages it added and ops.ShiftBookmarks(marks, from, by) is the same rule for the /Outlines tree — which is what -bookmarks does, so the printed number and the bookmark land on the same page. An entry pointing at a page the document has not got is refused by name rather than printed.

It runs onto as many pages as it needs, because a table of contents quietly missing its last nine entries is worse than one that refuses to be written: the first is a document that looks finished.

A caller that already has the entries, rather than a file of them, goes through ops.Nest([]Level) ([]Bookmark, error): a title, a page and a depth in reading order, which is what an /Outlines tree looks like once it has been walked. ParseOutline is that function with a parser in front of it. A row more than one level under the row before it is a *ops.DepthError naming the row — a tree with a rung missing is one nobody meant to ask for, and every way of guessing the missing level is a different document.

resize sets how big a page is; crop sets what of it shows. Two verbs, because they are two questions. A size is a box in points, or one of a3, a4, a5, letter, legal, tabloid — derived from their definitions rather than typed, so A4 is 210 × 297 mm at 72 points to the inch and not a number somebody copied. -landscape turns a named size on its side.

metadata writes what info prints. A key is given the way the PDF names it, with or without the leading slash, because a person reading info sees Title and should be able to type what they saw.

text -json writes the same reading as the lines, in a shape something else can parse without splitting on tabs. With -layout each run carries its position, its size, and whether it was invisible or unreadable — and those two are written even when false, because a reader that cannot tell "this run is readable" from "this tool did not say" is reading a guess.

text reads the page back as words, and -layout says where every piece of it sits — a page, a place, a size, and what it says. A piece the document gave no way to read comes back marked rather than guessed at, so you can tell a page that says nothing from one that could not be read. images writes out the pictures a page places, a JPEG as a JPEG.

Links and bookmarks are carried over and pointed at the pages they became here, so extracting three pages of a book leaves the links between those three working and drops the ones that led out of them. A link or a bookmark that already led nowhere in the source keeps its place without a destination, because a file with broken bookmarks should keep its shape rather than lose it.

The catalogue is always written from nothing, so a document-level script, an action that runs on opening, or a tree of embedded files never survives any operation at all. sanitize deals with what travels attached to a page: its own actions, an annotation's actions, JavaScript, launching, form submission, the annotation types that exist to play or embed something, and files associated with a page. A link to the web is not executable and stays.

What a screen reader follows

A tagged document says which run of marks on which page is a heading, a paragraph, a table cell, the label of a form field. That is the reading order a screen reader follows, and for a government form it is often what the law requires — RGAA in France, Section 508 in the United States, EN 301 549 in the EU. It cannot be copied across a rebuild: every part of it points into the document, and the number tree that indexes it is keyed by a number each page carries. So it is rebuilt, element by element, around the pages that survived, and those numbers are handed out afresh. A page that kept the number it had in a file it is no longer part of is a page a reader would look up and be told, with every confidence, about somebody else's.

An element whose every page has gone is removed and its parent pruned; one with some pages gone keeps the children that are left. An empty table cell is kept, because the shape of a table is part of what it says. A page written twice carries the structure once, on the first copy, since an element names one page. Merging two files carries no tree at all: two files have two role maps in which the same name may mean two different things, and there is no honest way to choose between them.

Of 1 633 real government forms from eighteen issuers, 1 021 carry a structure tree. After a rotate 1 014 still do — the seven that do not are the seven whose tree was empty in the file we were given — and 991 of the 1 021 are identical down to the last element, mark and annotation reference. The thirty that differ are accounted for one by one in the commit that added this. What cannot be carried is named in catalogue.go with the reason, rather than disappearing quietly.

Text is drawn in the four faces every viewer already has — Helvetica, Helvetica-Bold, Courier and Courier-Bold — so nothing is embedded and a watermark costs about a kilobyte. Stamp text may say {page}, {pages} and {n}, the last being a counter for serial numbering.

⛔ What a rewrite carries, audited rather than assumed

Twice in one afternoon this package was found to be dropping a catalogue entry whose absence is not "no opinion" but a default — so the loss changed the document silently. So the whole list was measured: a document holding twenty-three catalogue entries, a watermark over it, and of each entry the question what would its absence MEAN?

/PageLabels the viewer numbers pages by position — a book's front matter came back 1, 2, 3 instead of i, ii, iii
/OCProperties everything optional becomes visible — a hidden layer was revealed
/OutputIntents no colour management: a prepress file lost the ICC profile it declares, and would print differently with nothing to say why
/URI relative links resolve against wherever the viewer thinks the document is — the link is not removed, it is silently pointed elsewhere

All four are carried now, the first two rebuilt (they cannot be copied: one is keyed by page index, the other names objects the content reaches another way) and the last two copied.

What is deliberately not carried, and why
  • /OpenAction, /AA — what the document does when it is opened. Dropping them is safer, and is what sanitize exists for: carrying them would carry code across a rebuild;
  • /Legal, /DSS — a signature's attestation and its validation data. A rewrite has already invalidated the signature the moment it changed a byte, and carrying the validation data of a signature that no longer verifies would say the document is still attested when it is not;
  • /Threads, /Collection — these point into the document, at pages and at embedded files, which is why /Names /Dests is not carried either.

⛔ And three the audit reported as lost that are not: /AcroForm, /Outlines and /StructTreeRoot are all carried. The audit's fixture held an empty one of each, and an empty form, outline or structure tree is deliberately not written. A measured absence has to be read before it is believed — which is the other half of why an audit is worth running.

Verified against real files

Every operation is checked on the same corpus of 118 863 real PDFs the reader is measured against — Matplotlib, cairo, pdfTeX, Ghostscript, Adobe, R, Apache FOP, PDF 1.3 through 1.7. For each of the 118 833 that open, four properties have to hold, compared on the bytes of every page's content stream rather than on an exit status:

  • writing the document unchanged reproduces every page;
  • reversing twice is the identity;
  • merging a document with itself doubles it exactly;
  • selecting the last page yields exactly that page.

All four hold on all 118 833 files.

Laying pages out is checked the same way: for each of the 1 959 multi-page files in that corpus, two-up produces the right number of sheets and every form drawn on them carries exactly the bytes of the page it stands for, blanks included. All 1 959 hold.

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.

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 · playground 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/ops authors.

Forms

pdfops fields lists what a form asks for and what it holds; pdfops fill fills it in and saves it; pdfops addfields puts new fields into a document that has none, or adds to the form it already carries.

$ pdfops fields fw9.pdf
note: the file also carries an XFA form, which is not read; the standard one is.
topmostSubform[0].Page1[0].f1_01[0]                       text      ""
topmostSubform[0].Page1[0].Boxes3a-b_ReadOrder[0].c1_1[0] checkbox  "Off"
                                                            buttons [1]

$ pdfops fill -set 'topmostSubform[0].Page1[0].f1_01[0]=Wolfgang Amadeus Mozart' \
              -set 'topmostSubform[0].Page1[0].Boxes3a-b_ReadOrder[0].c1_1[0]=1' \
              fw9.pdf filled.pdf
Creating a form

pdfops addfields is the other half of fill, which can only change a field the document already has. The fields are described in a JSON file, because the thing being described is a layout and a command line is a poor place to put one.

$ cat fields.json
[
  {"name": "applicant", "kind": "text", "required": true,
   "widgets": [{"page": 1, "rect": [72, 700, 300, 720]}]},
  {"name": "agree", "kind": "checkbox", "value": "Yes",
   "widgets": [{"page": 1, "rect": [72, 670, 86, 684], "on": "Yes"}]},
  {"name": "size", "kind": "combo",
   "options": [{"value": "s", "label": "Small"}, {"value": "l", "label": "Large"}],
   "widgets": [{"page": 1, "rect": [72, 630, 220, 650]}]}
]

$ pdfops addfields -fields fields.json blank.pdf form.pdf
added 3 field(s)
$ pdfops fields form.pdf
applicant  text      ""   required
agree      checkbox  "Yes"  buttons [Yes]
size       combo     ""   row "s" row "l"

The kinds are text, checkbox, radio, button, combo, list and signature — the names pdfops fields prints, so a description can be written from a listing. A field showing in several places is one field with several widgets, which is what a radio group is.

It refuses before it writes, because each of these makes a file that opens and is broken: a field with no name (a field is addressed by its name), a choice field with no rows, a checkbox whose on-state is Off (the name the format reserves for not chosen), two widgets of one radio group in the same state, a comb field with no maxLen, an empty rectangle, a page the document does not have, and two fields of one name — the reader keys fields by name, so the second would silently shadow the first.

Unknown keys in the description are refused too: "mutliline" is a form missing the thing it was written to ask for, and a parser that ignores what it does not know says nothing about it.

Two details the format makes easy to get wrong, both held by tests:

  • A checkbox's drawing is not generated by the viewer. NeedAppearances covers text and choice fields, but a button shows whatever its own appearance dictionary holds for the state it is in, so one written without them is a box that never looks ticked however often it is clicked. One is drawn for each state, with the path operators rather than with a font, so the document needs no ZapfDingbats to show a tick.
  • A widget is marked Print. Without it the field is on screen and gone from the paper, which is where a filled form is most often looked at.

Signing a document

ops.Sign adds a digital signature (ISO 32000-1 §12.8) as an incremental update, written by the same appender fill uses: the original bytes are the start of the result, so every earlier signature still verifies.

signed, err := ops.Sign(pdf, ops.SignOptions{
	Signer: key, Certificate: cert, Chain: intermediates, // RSA, ECDSA or Ed25519
	Field:  "approval",          // an existing empty signature field, or a new invisible one
	Reason: "I agree", Location: "Paris",
	SubFilter: ops.PKCS7Detached, // or ops.CAdESDetached
})

What is written: an uncompressed signature dictionary whose values are all direct (Table 252), a /ByteRange of fixed-width numbers filled in after layout, a /Contents placeholder sized by signing once beforehand (or by Reserve), the signature field and its widget on the page, and /SigFlags 3 in the form dictionary. The CMS is a detached SignedData from go-authn/cms, with the signing-certificate-v2 attribute and no signing-time attribute; the time is /M. CAdESDetached writes the ETSI.CAdES.detached sub-filter. This repository does not claim conformance to a PAdES baseline profile, because that standard has not been checked here.

Refused, each with a sentinel: an encrypted document (ErrEncrypted: 32000-1 does not exempt /Contents from encryption, so nothing is guessed), a signature larger than its reserve (ErrReserveTooSmall), a field that already holds a signature (ErrFieldSigned), and a field name that belongs to some other kind of field (ErrNotSignatureField), a nil signer or certificate (ErrNoSigner), input that is not a readable PDF (ErrNotReadable) and a file that cannot be appended to (ErrNotAppendable: no usable startxref, or one that had to be repaired to be read).

From the command line, with PEM files (PKCS #8, PKCS #1 or SEC 1 key; an encrypted key is refused; key and certificate files over 1 MiB are refused):

pdfops sign -key key.pem -cert cert.pem -reason "I agree" contract.pdf signed.pdf
pdfops sign -key key.pem -cert cert.pem -chain ca.pem -field approval -subfilter cades form.pdf signed.pdf
Signing with a .p12 / .pfx file

A certificate export from Windows, macOS, Firefox or a certificate authority is one password-protected PKCS #12 file (RFC 7292) holding the key, the certificate and its chain. SignOptions.LoadPKCS12 reads it with go-authn/pkcs12 and sets Signer, Certificate and Chain; nothing else of the options changes, and nothing is kept:

var o ops.SignOptions
if err := o.LoadPKCS12(p12, password); err != nil {
	// errors.Is: ErrPKCS12Password, ErrPKCS12Unsupported,
	//            ErrPKCS12TooLarge, ErrPKCS12Malformed
}
o.Reason = "I agree"
signed, err := ops.Sign(pdf, o)

A wrong password and a damaged file are one answer (ErrPKCS12Password): the format's MAC cannot tell them apart. An algorithm or key this cannot read, a file with no MAC, and an X25519 key (it cannot sign) are ErrPKCS12Unsupported; a RSA key without CRT values is one of them. Each error also wraps go-authn/pkcs12's own, so errors.Is answers for either. ErrPKCS12TooLarge covers every bound of go-authn/pkcs12: MaxPKCS12Size (8 MiB, the file; check it before reading, as the command does), 1 000 000 iterations per derivation, 32 KiB per certificate, an RSA modulus of 8192 bits. A decode allocates up to about 25 MB for a hostile file, so a service should cap the decodes in flight.

pdfops sign -p12 me.p12 -p12pass me.pass -reason "I agree" contract.pdf signed.pdf
pdfops sign -p12 me.p12 -visible 50,50,250,110 contract.pdf signed.pdf

The password is never an argument or an environment variable: another process can read both. -p12pass names a file holding it (one trailing line ending is dropped), or is - to read it from standard input, up to 4098 bytes and with one trailing line ending dropped (printf %s "$PW" | pdfops sign -p12 me.p12 -p12pass - in.pdf out.pdf; refused when standard input is also the PDF input; when standard input is a terminal, -p12pass - gets the same no-echo prompt as omitting it); without it, pdfops asks on the terminal with no echo, and refuses, saying so, when standard input is not a terminal. -p12 replaces -key and -cert; giving both is refused; -chain still adds certificates. The empty password is tried before the absent one, as exporters differ. A password pkcs12 cannot use at all (not valid UTF-8, over 1024 characters) is also ErrPKCS12Password, with a message saying so. pdfops reads only regular files (a FIFO or a device given for any file is refused: each is opened without waiting and examined once open, so a path swapped for a FIFO in between cannot hang it), zeroes the password buffer after use, and puts the terminal back if Ctrl-C, Ctrl-\ or a kill arrives at the prompt. A Go string cannot be erased, so a library caller who cares should keep the password in a []byte, convert it for the one call, and zero it; do not zero the file's bytes, the certificates may point into them.

The certificate is not judged. LoadPKCS12 does not check its validity dates, its key usage or extended key usage, or its chain to a root: it loads a key, a certificate and the certificates beside it. The caller decides whether to sign with it, and the verifier decides whether to trust the result.

A visible signature

SignOptions.Appearance gives the signature a box on its page. nil (the default) keeps it invisible, and the bytes written are then exactly what they were before Appearance existed (a golden SHA-256 test pins that).

signed, err := ops.Sign(pdf, ops.SignOptions{
	Signer: key, Certificate: cert, Page: 1,
	Appearance: &ops.SignAppearance{
		Rect:  [4]float64{50, 50, 250, 110}, // x0 y0 x1 y1, in the page's points
		Image: logoPNG,                       // optional; its aspect ratio is kept, fitted and centred
		Text:  "Approved\nM. Martin",         // optional; Helvetica, wrapped; \n starts a line
		// FontSize 0 = the largest up to 24 pt that fits; Color is RGB 0..1, zero = black.
	},
})

With neither Image nor Text the box says "Digitally signed by " and the signing time (RFC 3339, UTC). For an existing empty signature field, a zero Rect means the field widget's own /Rect. The widget gets /F 4 (Print), the /Rect and an /AP /N form holding the picture and the text. All of those objects are written in the same incremental update as the signature, so they are inside the /ByteRange: an appearance edited after signing breaks the signature (tested).

Only the field's first widget gets the appearance. The text is Helvetica in WinAnsiEncoding, so a character that encoding has no code for (Cyrillic, CJK, an emoji) is refused, not dropped: ErrAppearanceText names the first one and asks for a Text that can be drawn. That includes the default text when the certificate's common name has such a character (a Cyrillic signer must pass a Text, or an Image). Drawing them needs a Unicode (Type0) font, which is future work.

Refused, each with a sentinel: a box that is not finite, is inverted, has no area or has a coordinate beyond 14400 points, the page limit of ISO 32000-1 Annex C (ErrAppearanceRect), a box lying outside the page by more than its own size, the page being its /CropBox when it has one and its /MediaBox otherwise (ErrAppearanceOffPage), an image that does not decode or is over MaxPixels (ErrAppearanceImage), text over 4 KiB or that cannot be drawn (ErrAppearanceText), a font size that is neither 0 nor from 1 to 1000, or a colour that is not finite (ErrAppearanceFontSize, ErrAppearanceColor), and an existing field with no widget, or none with a usable rectangle when none was given (ErrNoFieldRect).

pdfops sign -key key.pem -cert cert.pem -visible 50,50,250,110 -text "Approved" contract.pdf signed.pdf
pdfops sign -key key.pem -cert cert.pem -visible 50,50,250,110 -image logo.png contract.pdf signed.pdf

-visible is four numbers on -page; -image is read up to 16 MiB; with -field naming an existing signature field, -visible may be left out. The drawn page is checked in the tests by rendering it, and the bytes by pdfsig, qpdf --check and reader/signature.

Judged by three independent tools on every key kind, for a plain cross-reference table and a cross-reference stream, with and without a prepared field, signed once and then again:

key poppler pdfsig 26.10 reader/signature openssl cms -verify qpdf --check
RSA both valid, last "Total document signed" valid, whole, dictionary signed valid no new warning
ECDSA both valid, last "Total document signed" valid, whole, dictionary signed valid no new warning
Ed25519 "Signature is Invalid" (NSS) valid, whole, dictionary signed valid no new warning

The Ed25519 row is poppler's verdict, and it is recorded rather than asserted. Both of the other judges accept the same bytes. A property test flips bytes across both signed ranges, and none of the flips leaves a valid whole-file signature. CI installs the three tools and fails, rather than skips, when one is missing.

Workflows: pdfops workflow

pdfops workflow runs a graph of the verbs above, the way the PDF Workflow Builder of BentoPDF does. The file is BentoPDF's own JSON (src/js/workflow/types.ts, SerializedWorkflow): {version, nodes:[{id,type,position,controls}], connections:[{id,source, sourceOutput,target,targetInput}]}. A file exported from its editor runs here, for the node types both have; the Go package is github.com/go-pdfkit/ops/workflow.

$ pdfops workflow check flow.json
warning: node mid: Watermark: controls not honoured here: angle, opacity
ok: 3 nodes, 2 connections

$ pdfops workflow run -o out.pdf flow.json in.pdf
wrote out.pdf (PDF)

$ pdfops workflow run -secrets pw.json -o out.zip flow.json a.pdf b.pdf
wrote out.zip (ZIP of 2 PDFs)

$ pdfops workflow nodes

One PDF comes out as a PDF, several as a ZIP, as BentoPDF's Download does.

  • What is checked, before anything runs. Typed sockets (PDF, MultiPDF, Image), cycles, at least one input and one output node, Encrypt as the last processing step, input sockets that take one connection, fan-out. A node type the file uses but this build does not know is reported by name, never dropped: BentoPDF skips it silently on load.
  • What runs. 29 of BentoPDF's 74 node types, in topological order, one verb each (pdfops workflow nodes prints the table). The other 45 (the converters from Word, images, e-mail and the like, OCR, digital signature, PDF to image or text, colour effects, and so on) have no verb here and are refused, naming the node. A control that BentoPDF has and a verb here cannot honour (a watermark's opacity, say) is a warning, not silence.
  • A failing node stops the run and is named: Rotate (node n3): control "angle": 999 is outside -360..360.
  • Passwords are never in the file. A control whose name holds pass, secret or token is blanked when the file is read and when it is written. A node that needs one (Encrypt: userPassword, ownerPassword; an input of an encrypted PDF: password) reads it from -secrets <file.json>, {"nodeId":{"userPassword":"…"}}, never from the command line; the global -password applies to every input node.
  • A workflow file is untrusted input. At most 1 MiB, 256 nodes, 1024 connections, 64 controls of at most 1000 bytes each, a fan-out of 16; the run is bounded to 20000 pages and 512 MiB in and out, counted per node, and a Posterize feeding a Posterize is refused before the pages are made. The parser and the validator are fuzzed, the corpus is committed.

Marking text: pdfops mark

pdfops mark writes the marks a reader makes over a page rather than on it — a highlight, an underline, a strikeout or a squiggly underline (ISO 32000-1, §12.5.6.10, Table 179).

$ pdfops mark -area 1:72,700,300,712 -note "worth coming back to" paper.pdf marked.pdf
marked 1 area(s) as highlight

$ pdfops mark -area 1:72,700,300,712 -and 1:72,686,250,698 -as underline paper.pdf marked.pdf
marked 2 area(s) as underline

An area is page:x0,y0,x1,y1 in points, counting up from the foot of the page — the space a PDF is written in. -and marks another area; each one becomes its own annotation, because a markup annotation's several quadrilaterals are for the several lines of one selection ("each quadrilateral shall encompass a word or group of contiguous words"), and two unrelated marks in one annotation would share a note, a colour and a date, and come off together.

⛔ The page's own content is not touched. That is the whole reason to write an annotation rather than draw on the page: the glyphs underneath are unchanged, the mark comes off again by dropping the annotation, and a reader who wants the document as its author wrote it gets it.

Three details the format makes easy to get wrong, each held by a test that renders the page and looks at the pixels:

  • A mark with no appearance stream is invisible. Table 179 says /AP "shall take precedence over QuadPoints"; go-pdfkit/render draws an annotation only from its appearance and skips one that has none. So a highlight written with QuadPoints alone is a perfectly correct annotation that nothing shows.
  • A highlight is translucent, not multiplied. Multiply is what a highlighter physically is and what Acrobat writes, but render implements no blend modes at all — a Multiply highlight paints an opaque block over the sentence it marks. Constant alpha is understood everywhere and leaves the words legible.
  • The vertex order follows Table 179's figure, not its prose. The text says the four vertices are "counterclockwise"; Figure 64 shows (x1,y1) and (x2,y2) along the top edge and (x3,y3), (x4,y4) along the bottom — a Z. Every widely used reader follows the figure. The Quad type names its corners rather than taking eight numbers, so the mistake cannot be made silently.

And the marks are flagged Print, for the same reason a widget is: without it a highlight vanishes the moment somebody prints what they marked up.

Redacting text: removing it, not covering it

Doc.Redact takes the text inside a region out of the page's content stream. ISO 32000-1 §12.5.6.23, on applying a redaction:

Conforming readers that support redaction annotations shall provide a mechanism for applying content removal, and they shall remove all traces of the specified content. If a portion of an image is contained in a redaction region, that portion of the image data shall be destroyed; clipping or image masks shall not be used to hide that data.

⛔ A black rectangle is not a redaction. It is the standard data leak: the text is still in the content stream, so anyone's copy and paste — or pdfops text — reads it straight back out from under the box. So the test that decides whether this is a redaction at all is not about how the page looks, it is that the redacted string does not appear in the bytes that come out, and a drawn rectangle fails it.

The operator that drew the text is overwritten with spaces of its own length, which does two things at once: the string is gone from the stream, and every offset after it is still where it was, so the text that stays does not move. extract.Run.Op says which bytes to overwrite — deciding which glyphs are inside a region is work extract already does, and a second implementation of it here would cut the document somewhere other than where the caller was told the text was.

The region is then painted over, because an area that was emptied and not marked cannot be told from one that was always blank. That paint is a marking, not the redaction: the text is already gone when it is drawn.

⛔ And it refuses rather than half-redacts, naming the page and the reason. A caller who is told can choose another region or another tool; a caller who is not told believes the document safe to send. It refuses a region holding:

what why
text inside a Form XObject the bytes are not the page's, and an XObject is shared — cleaning one page would change every page that draws it. RecolourText stops at the same wall
an image this release cannot rewrite a plain one is no longer refused: its samples are destroyed and it is written back, which is what §12.5.6.23 asks for. What is refused is a picture whose samples cannot be put back truthfully — see destroying the pixels below
an annotation its own /Contents can hold the very words being redacted
an annotation this document has added and not yet written a mark or a widget is held until the write, because each names the page object it sits on, so neither is in the source file — and reading only the source missed them. The workbench walked into it: highlight a line, then decide to redact it, and the text went while the note quoting it stayed. Drop the mark or the field first
an operator only part of whose text is inside the region blanking it would remove text nobody asked about, and the surviving words cannot simply be re-emitted: the bytes in the stream are font codes, and Unicode does not round-trip back to them through a CID font's map. Keeping the survivors' original bytes and replacing the removed ones with an equivalent kern is the way, and it is next
text that reaches outside the region a run is the unit that can be removed, so a producer drawing a whole line with one Tj makes that line the run — and redacting one word of it would take the line. That is not a leak, which is why it is tempting to allow; it is the other way a redaction betrays its caller, by removing what they did not ask about and not saying so. A region is allowed to miss a run's own box by up to two points, because a caller mapping a lit rectangle back into page space arrives through screen pixels

The refusal happens when Redact is called, not when the document is written — by the time of Bytes the caller has already been promised a redacted document by everything in between.

Destroying the pixels

§12.5.6.23 is explicit that a clip or a mask will not do, so the samples under the region are overwritten and the picture is written back. A scanned page is one picture, so without this the verb refused everything a scanner produces.

What this does it to is a picture whose samples are plain — one the reader has already unfiltered — or a JPEG, eight bits a component, DeviceGray or DeviceRGB, drawn upright and drawn once on the page. Each of the others is refused by its own name, with the reason:

refused why
still JPXDecode, or any other filter this does not undo its samples would have to be decoded and written back, and a decoder this does not have is not one to guess at
drawn turned or skewed the box a turned picture covers looks exactly like the box an upright one covers, so mapping the region into its samples by that box would destroy more than was asked for — which is the other way a redaction betrays its caller. extract.Image.Matrix exists for this: b and c are zero for an upright picture, and stay zero for a flipped one
drawn more than once on the page replacing the picture replaces it for every Do that names it, so blanking it for one placement blanks it for the others, in a different place each time
an inline image it is written into the content stream rather than held as a resource, so there is nothing to write back in its place
/ImageMask, /SMask, /Mask, /Decode each changes what a sample means, and a sample set to zero under one of them is not necessarily a destroyed one
/Indexed, /ICCBased, /DeviceCMYK, anything else in an indexed space a zero is the palette's first colour, which may be white; in the others the component count has to be read out of a stream. What a destroyed sample holds there is not something to guess at
samples that are not all there the stream is shorter or longer than Width × Height × components, so what is in it is not what it says
A JPEG is written back as plain samples, not as another JPEG

⛔ Re-encoding would change the pixels nobody asked about. A JPEG is re-quantised block by block, so writing the blanked picture back as a JPEG would degrade every block of it — the whole photograph, to destroy a corner of it. What this writes instead is exactly what a reader of the original would have seen, with the region destroyed, and the test for it decodes the original itself and compares the kept samples byte for byte against that decode. Asserting a colour would be asserting what an encoder does with it, which is a different subject and a moving one.

The picture loses its compression: a photograph as Flate is several times the same photograph as a JPEG, and that is the trade. It is paid only by a picture a region actually reaches — one nobody redacted over keeps its DCTDecode stream byte for byte.

Two more refusals belong to this path:

refused why
a CMYK JPEG there is no faithful CMYK to RGB without the output profile the file does not carry, so a conversion here would change every colour on the page
more than 100 megapixels a JPEG says how big it is in a handful of bytes and the decoder then allocates width × height × 3, so a file of twenty-five bytes can ask for gigabytes. The size is read from the header and refused before anything is decoded — checking after the decode is checking after the allocation. A 600 dpi A4 page is about 35 megapixels

The test for that ceiling is a real bomb — thirty-nine bytes declaring 20000 by 20000 and not one sample — run against the real bound rather than a knob lowered for the occasion, and it asserts that the decoder was never reached: the refusal message alone reads the same whether the check runs before the decode or after it.

⛔ The original picture is not left in the file. The page's /Resources are rebuilt with the blanked picture in place of the original rather than copied — copying them would have written the original into the output beside the blanked one, referenced by nothing and holding every pixel the redaction promised to remove. That is exactly the shape of the leak fixed in #74, one object along, and the test for it walks every object of the written file and decodes it, because a picture's samples are compressed and a raw grep cannot see them.

⛔ And the sample grid counts down while the page counts up. A picture occupies the unit square of the transform in force, where v runs from its bottom edge to its top, while sample row zero is its top row. Reading one for the other blanks the mirror image of what was asked for, which looks like a redaction until somebody compares it with the page. A region ending part way into a sample destroys all of that sample: a third of a secret is a secret.

A redaction also survives the rest of the verbs. That is worth saying because the write path once dropped a rewritten content stream whenever it stamped a page: for a recolouring that loses a colour, but for a redaction it would put the removed text back and draw the fill over it, so the document would look redacted and not be. There is a test that redacts and watermarks the same page and then looks for the string.

A document assembled from several files can still be given a form: two sources' forms cannot be merged — their fields may be named the same — but fields the caller asked for come from neither source and so are in no conflict.

A filled form is written as an incremental update: the original file, byte for byte, with the objects that changed appended after it and a new cross-reference section pointing back at the old one. That is how every program that saves a form saves one, and it is the safest thing a program can do to somebody's document — nothing already there is rewritten, so whatever this does not understand survives untouched, and if the update is wrong the original is still the first part of the file.

The update says where its objects went the same way the file already does. A file whose cross-reference is a stream cannot be pointed back at by a plain table: a reader following /Prev would find an object where it expected the word xref. That is not a nicety — macOS's own renderer draws nothing at all for such a file, which is how the mistake was found.

Two things it will not do. A document that had to be repaired to be read has no cross-reference section worth pointing back at, so it is refused rather than added to. A document that is encrypted has every string and stream in it written through a key, and this does not yet write into one.

Measured on a real form: fw9.pdf filled in every field, written out, read back with every value in place, and rendered by macOS — which drew what we drew, in the same places, comb cells and ticks included.

⚠ Filling a form is the only verb that keeps one. Every other verb here takes the pages apart and builds a new document round them, and a form is tied into a document by object number in a dozen places at once — so merging, splitting or rotating a form's pages loses the form. Use fill on the file itself.

The form inside a blank document

Some PDFs are blank to look at and are not blank. Their pages hold one panel — "Please wait... your PDF viewer may not be able to display this type of document" — and the real form exists only as XML beside them, laid out when Adobe's own reader opens it. Adobe removed the format from PDF 2.0; no browser and no other reader lays one out.

pdfops xfa lays it out and draws it, which turns such a file into one anything can show.

$ pdfops xfa t1135-fill-23e.pdf readable.pdf
6 sheets, 497 elements drawn

Measured over every dynamic form in a corpus of 2 240 real government forms — fourteen of them, from the Canada Revenue Agency, the French cerfa series, the US Department of Labor and the Office of Personnel Management: all fourteen laid out, 111 sheets, 9 808 elements, nothing left unplaced, and every file read back by poppler.

WHERE each element goes is go-pdfkit/xfa's, measured against pdf.js and pdfium. What is drawn INSIDE each box is this package's own and much simpler: the four standard faces, a greedy line break, a rule round each field. So this is legibility rather than fidelity — the difference between a blank sheet and a form somebody can read, not between this and Adobe.

Pictures are drawn — 27 of them across twelve of the fourteen. For most that is a logo; for French cerfa 12064 it is the whole printed form. That one carries 212 fields, 7 draws, 4 images and — counted, not guessed — no <text> and no <caption> whatever, so without its pictures it is a grid of empty boxes and with them it is the customs declaration it is. How big each one is drawn follows pdfium's own arithmetic (xfa/fxfa/cxfa_ffwidget.cpp:55-86), because pdf.js declines to settle fit and actual and leaves them to a browser's sizing of an <img>.

A picture's own size is its pixels at its own resolution, read from a PNG's pHYs chunk or a JPEG's JFIF density, and that is not a detail. Every Canada Revenue Agency form in the corpus writes aspect="actual", and their logos are 1200-dpi PNGs: 2617 pixels across is 157.02 points, which is to a hundredth of a point the width the template writes for the box. Taken at 72 dpi — one point per pixel, the assumption for a picture that declares nothing — the same logo is 2617 points wide and covers a third of the sheet in black. It did, until the render was looked at.

Page numbers come out right — "Page 3 of 11", and "Page 3 sur 4" on a French form — without running the form's scripts. A footer like that is not text: it is rich text holding a floating field naming a hidden field whose value a script sets. All sixteen of those in the corpus ask one of exactly two things:

this.rawValue = xfa.layout.page(this);
this.rawValue = xfa.layout.pageCount();

Those are questions asked of the layout, which has just answered them. Recognising the two and handing back what the pager computed is not evaluating anything. Neither reference does this — pdf.js's layout ignores xfa:embed entirely, pdfium runs a JavaScript engine — so it is named as ours. Anything else a floating field names is left as a gap, because a wrong number that looks right is worse than a blank: four cerfa fields carry a static default beside their script, and printing that would put "Page 1 of 1" on every sheet.

Two limits, both named rather than left to be discovered:

  • A picture in a file outside the document is not fetched. That is pdf.js's position and its words: "we don't get remote data and use what we have in the pdf itself, so no picture for non null href". Two of cerfa 12818's are like that, and both name an absolute path on the machine of whoever drew the form — C:\Users\…\Downloads\logo ministere.PNG. They are reported, not passed over.
  • Text is set smaller rather than cut off. The box was measured with the font the template names and this draws in Helvetica, which is wider; at the template's own size the words come to more lines than the box holds. The size comes down until they fit, with a floor of four points, because losing the end of a sentence is worse than setting it a point smaller.

Documentation

Overview

Package ops is the verb layer of go-pdfkit: what people actually do to a PDF they already have. Merge two files, pull out pages three to seven, turn a page the right way up, drop the metadata, split a report into chapters.

A document here is an ordered list of pages, each borrowed from a source file, plus the document-level pieces. Every operation rearranges that list or annotates its entries, and nothing is applied until Doc.Bytes is called. An operation therefore costs nothing until it has to, pages from several files mix freely, and the list stays a plain value.

Index

Constants

View Source
const (
	// MaxInvisibleWords is the most words one page may carry.
	MaxInvisibleWords = 100000
	// MaxInvisibleWordRunes is the most characters one word may have.
	MaxInvisibleWordRunes = 4096
)

Bounds on what AddInvisibleText accepts. The words come from a recogniser, which is to say from the content of a scan somebody else made, so each of these is a limit on what a hostile or merely confused page can make this package allocate.

View Source
const (
	// PKCS7Detached is adbe.pkcs7.detached: a detached CMS SignedData over the
	// byte ranges.
	PKCS7Detached = "adbe.pkcs7.detached"
	// CAdESDetached is ETSI.CAdES.detached. The CMS is the same detached
	// SignedData, carrying the signing-certificate-v2 attribute and no
	// signing-time attribute (the time is the dictionary's /M). This package
	// does not claim conformance to a PAdES baseline profile: that standard
	// asks more than the shape of the CMS, and it has not been checked here.
	CAdESDetached = "ETSI.CAdES.detached"
)

SubFilter values a signature can be written with (Table 252, §12.8.3.3).

View Source
const MaxPKCS12Size = pkcs12.DefaultMaxInputSize

MaxPKCS12Size is the largest .p12 / .pfx file LoadPKCS12 reads. A real one is a few kilobytes; the bound is go-authn/pkcs12's own default for an input.

Variables

View Source
var (
	// ErrReserveTooSmall: the CMS signature came out larger than the space
	// reserved for it, so nothing was written.
	ErrReserveTooSmall = errors.New("ops: the signature does not fit in the space reserved for it")
	// ErrReserveTooLarge: more space was asked for than a signature may reserve.
	ErrReserveTooLarge = errors.New("ops: the space asked for the signature is larger than the most one may reserve")
	// ErrFieldSigned: the field named already holds a signature.
	ErrFieldSigned = errors.New("ops: the signature field is already signed")
	// ErrNotSignatureField: the field named exists and is not a signature
	// field.
	ErrNotSignatureField = errors.New("ops: the field is not a signature field")
	// ErrNoSigner: SignOptions has no Signer or no Certificate.
	ErrNoSigner = errors.New("ops: a signature needs a signer and its certificate")
	// ErrNotReadable: the input is not a PDF the reader can open.
	ErrNotReadable = errors.New("ops: the input cannot be read as a PDF")
)

The refusals a signature can meet, besides ErrEncrypted.

View Source
var (
	// ErrPKCS12Password: the password is wrong, or the file was changed after
	// it was made (the format cannot tell the two apart, by design), or the
	// password cannot be used at all (not valid UTF-8, over 1024 characters;
	// errors.Is(err, pkcs12.ErrPassword) tells that case).
	ErrPKCS12Password = errors.New("ops: the .p12 password is wrong, or the file is corrupted")
	// ErrPKCS12Unsupported: a well-formed file that uses an algorithm or a key
	// this cannot read, or a key that cannot sign a PDF (X25519).
	ErrPKCS12Unsupported = errors.New("ops: the .p12 uses an algorithm or key type that is not supported")
	// ErrPKCS12TooLarge: the file, or something it asks for (iterations,
	// certificates, key size), is over a bound.
	ErrPKCS12TooLarge = errors.New("ops: the .p12 is larger or costlier than the bounds allow")
	// ErrPKCS12Malformed: the input is not a readable .p12, holds no private
	// key or no matching certificate, or holds more than one key.
	ErrPKCS12Malformed = errors.New("ops: the file is not a usable .p12")
)

The refusals LoadPKCS12 can meet. Each wraps the go-authn/pkcs12 error it stands for, so errors.Is answers for either.

View Source
var (
	// ErrAppearanceRect: the box is not finite, is inverted, has no area, or
	// has a coordinate beyond 14400 points.
	ErrAppearanceRect = errors.New("ops: the signature's box is not a box with an area, within 14400 points of the origin")
	// ErrAppearanceOffPage: the box lies outside the page's MediaBox by more
	// than the box itself.
	ErrAppearanceOffPage = errors.New("ops: the signature's box is far outside the page")
	// ErrAppearanceImage: the image is over the pixel ceiling or does not decode.
	ErrAppearanceImage = errors.New("ops: the signature's image cannot be used")
	// ErrAppearanceText: the text is longer than maxAppearanceText bytes, or
	// holds a character Helvetica in WinAnsiEncoding cannot draw (the message
	// names the first). That is also true of the default text, which is made of
	// the certificate's common name: pass a Text that can be drawn. A Unicode
	// (Type0) font appearance is future work; nothing is dropped meanwhile.
	ErrAppearanceText = errors.New("ops: the signature's text cannot be drawn")
	// ErrAppearanceFontSize: the font size is not finite, or is a non-zero
	// size outside minFontSize..maxFontSize points.
	ErrAppearanceFontSize = errors.New("ops: the signature's font size is not 0 (fitted) or a number from 1 to 1000")
	// ErrAppearanceColor: a colour component is not finite.
	ErrAppearanceColor = errors.New("ops: the signature's colour is not made of finite numbers")
	// ErrNoFieldRect: the field being signed has no usable /Rect and none was
	// given.
	ErrNoFieldRect = errors.New("ops: the signature field has no usable rectangle, and none was given")
)

The refusals an appearance can meet.

View Source
var ErrEncrypted = errors.New("ops: the document is encrypted, and this does not yet write into one")

ErrEncrypted is what adding to an encrypted document is refused with. A document written through a key has every string and every stream in it written through that key too, so anything appended would have to be as well. That is not done here, and writing an update in the clear beside encrypted objects makes a file nothing can read.

View Source
var ErrNotAppendable = errors.New("ops: the file cannot be appended to")

ErrNotAppendable is what a file that cannot be added to is refused with: one that does not say where its cross-reference section is, or that had to be repaired to be read.

View Source
var ErrOutlineTooLarge = errors.New("ops: the text to outline is past the bounds")

ErrOutlineTooLarge is what outlining a page answers when the text it would write is past the bounds: a content stream can show a glyph per byte, and a glyph is tens of bytes of path, so the size of the result is not the size of the input.

View Source
var ErrOutlineVertical = errors.New("ops: a font written vertically cannot be outlined")

ErrOutlineVertical is what outlining answers for a font written top to bottom. The renderer this package takes its glyphs from does not place them, and paths drawn at places nobody has checked are worse than text left alone.

View Source
var ErrTooManyObjects = errors.New("ops: the update would number an object past the most a PDF may hold")

ErrTooManyObjects is returned when an update would number an object past the most a PDF may hold.

Functions

func BlankPages added in v0.15.0

func BlankPages(pdf []byte, opt BlankOptions) ([]int, error)

BlankPages reports which pages of a file hold almost nothing, counting from one and in order.

Each page is DRAWN and its pixels counted, because that is the only test that agrees with a reader. A page whose content stream is full of operators painting white, or drawing outside the media box, looks blank and is blank; a page carrying an image of nothing is blank too, and no amount of reading the content stream says so.

⛔ What it will not do is call a page of solid colour blank. The test is distance from WHITE, not uniformity: a deliberately black separator sheet carries information, and a measure of variance would delete it.

func FromXFA added in v0.12.0

func FromXFA(src *reader.Document) (*Doc, *XFAReport, error)

FromXFA lays out the XFA form a document carries and returns a document of its pages, drawn.

The source document's own pages are not kept: for a dynamic form they are the placeholder, and for a static one they are the form itself and this is the wrong verb — see forms.Form.Dynamic, which says which kind a document is. This does not refuse a static one, because a caller may legitimately want to see what the XML says as against what the pages show, but a caller that has not asked which kind it has will replace a perfectly good form with a plainer drawing of it.

func ParseRange

func ParseRange(spec string, pageCount int) ([]int, error)

ParseRange turns the page selection people write — "1-3,7,10-", "even", "last", "all" — into page numbers counting from one, in the order given and with duplicates kept, because "1,1,2" really does mean three pages.

A range with no start begins at the first page and one with no end runs to the last. A descending range like "5-2" counts down, which is how a reversed extract is written.

func Sign added in v0.39.0

func Sign(src []byte, o SignOptions) ([]byte, error)

Sign appends a signature to a document, as an incremental update, and returns the whole signed file. src itself is not modified, and is the first len(src) bytes of what is returned — or of it after a single line ending, when src does not end with one.

Types

type Attachment added in v0.10.0

type Attachment struct {
	// Name is what the document calls it.
	Name string
	// Description is what it says the file is, when it says anything.
	Description string
	// Data is the file.
	Data []byte
}

An Attachment is a file travelling inside the document.

type BlankOptions added in v0.15.0

type BlankOptions struct {
	// DPI is how finely the page is drawn before its pixels are counted. Zero
	// means a hundred and fifty.
	//
	// ⛔ It is not fifty, which is what this first used and what a thumbnail
	// would want. MEASURED on A4: at 50 DPI an eight-point full stop covers
	// exactly ONE pixel, which is the same mark a speck of dust makes, so no
	// threshold at that resolution can tell punctuation from dirt. At 150 it
	// covers four and a comma covers eight. See TestMeasureTheInkLadder.
	DPI float64

	// Tolerance is how far a channel may be from white and still count as
	// paper, out of 255. Zero means twelve.
	//
	// ⛔ Not zero-means-zero: nothing in a rendered page is exactly white.
	// Anti-aliasing, a JPEG background and a scan of real paper all land a few
	// levels below it, and a tolerance of zero calls every page inked.
	Tolerance uint8

	// MaxInk is the fraction of a page's pixels that may be ink and have the
	// page still count as blank. The zero value keeps any page with a mark on
	// it, which is what the zero value SHOULD mean here.
	//
	// For scans, where dust and the edge of the platen leave specks, the
	// figures to set it from are these, measured on A4 at the default 150 DPI:
	//
	//	one pixel            4.6e-07
	//	a full stop (8pt)    1.8e-06   (four pixels)
	//	a comma (8pt)        3.7e-06   (eight pixels)
	//	one word (12pt)      2.0e-04
	//
	// So 1e-06 tolerates a speck or two and still keeps a page holding a full
	// stop. The margin is a factor of four, and it is not offered as a default
	// because whether that margin holds depends on the scanner, which this
	// package cannot see.
	MaxInk float64

	// MaxPixels is passed to the renderer, so a media box a file made up
	// cannot be asked to fill memory.
	MaxPixels int

	// KeepAnnotations counts the notes, highlights and form fields a page
	// carries as ink. They are NOT counted by default: a page whose only mark
	// is a sticky note is blank paper somebody wrote on, and the note is not
	// part of what was printed.
	KeepAnnotations bool
}

BlankOptions say how little a page may hold and still count as blank.

⛔ The zero value is the STRICTEST setting, not a middle one: a page with a single inked pixel is kept. That is deliberate and it is the only safe default, because this is the input to deleting pages — a page wrongly called blank destroys content, while a blank page wrongly kept merely leaves a blank page.

type Bookmark added in v0.4.0

type Bookmark struct {
	Title    string
	Page     int
	Children []Bookmark
}

A Bookmark is an entry of an outline written from scratch: what it says, the page of this document it points at counting from one, and whatever sits under it.

It is what a document assembled rather than merged carries — a shared edit, a report built out of pieces — where there is no source outline to carry over because the outline is the caller's own.

func Nest added in v0.33.0

func Nest(rows []Level) ([]Bookmark, error)

Nest turns bookmarks in reading order into the tree SetOutline takes.

⛔ A row deeper than one level below the row before it is a *DepthError naming the row, because a level missing in the middle is a tree nobody meant to ask for and every way of guessing one is a different document.

⛔⛔ IT IS ONE ALGORITHM AND NOT TWO. A table of contents read as text and an /Outlines tree already in a document arrive the same way — a title, a page and a depth, in reading order — so the stack that turns depths into children lives here, once, and both ParseOutline and the browser workbench go through it rather than each keeping a copy.

func ParseOutline added in v0.32.0

func ParseOutline(text string) ([]Bookmark, error)

ParseOutline reads a table of contents written as text: one bookmark a line, a title, a TAB and a page number, with two spaces of indent for each level of nesting.

Introduction→1
  Why→2
Chapter one→7

⛔ A LINE IT CANNOT READ IS AN ERROR NAMING THE LINE, because a table of contents quietly missing an entry is worse than one that refuses to be written: the first is a document that looks finished and sends a reader to the wrong page. Blank lines are not entries and are not counted as any.

⛔⛔ IT LIVES HERE, IN THE LIBRARY, AND NOT IN THE COMMAND. It was written inside cmd/pdfops, where nothing else could reach it — so the browser workbench, asked for the same thing, would have had to carry a second parser for the same text. Two implementations of one published format are two things to keep in step, and the one that drifts is whichever has fewer users. The command now calls this, so the workbench and `pdfops outline -from` accept exactly the same file, by construction rather than by care.

func ShiftBookmarks added in v0.34.0

func ShiftBookmarks(marks []Bookmark, from, by int) []Bookmark

ShiftBookmarks moves the entries that point at page from or later on by n pages, which is what inserting pages in front of them does to a document.

⛔ It is here rather than written out by each caller because the rule has an edge: an entry pointing at a page BEFORE the insertion has not moved, and shifting it too would send a reader to the wrong place in exactly the documents that have a preface.

type Change added in v0.37.0

type Change struct {
	Kind ChangeKind
	// What says what changed, in the terms of the kind: the words for a text
	// change, the size and filter for a picture, the subtype and contents for
	// an annotation. Empty for a page added or removed, whose page numbers are
	// on the pair.
	What string
}

A Change is one difference found on one pair of pages.

type ChangeKind added in v0.37.0

type ChangeKind string

A ChangeKind says what sort of difference was found. They are the categories a reader filters by, and they are strings so that a report, a command and a workbench panel all name a change the same way.

const (
	// PageAdded and PageRemoved are pages the pairing could find no partner
	// for. ⛔ A page REPLACED wholesale is reported as both, because "this page
	// became that one" is a claim about intent that nothing in the file
	// supports: two pages with no words in common are two pages.
	PageAdded   ChangeKind = "page added"
	PageRemoved ChangeKind = "page removed"

	// TextAdded and TextRemoved carry the words themselves, in the order the
	// page draws them.
	TextAdded   ChangeKind = "text added"
	TextRemoved ChangeKind = "text removed"

	// PictureAdded and PictureRemoved carry a picture's size and how its
	// samples are stored. A picture whose BYTES changed is both: removed and
	// added, since there is no sense in which one bitmap "became" another.
	PictureAdded   ChangeKind = "picture added"
	PictureRemoved ChangeKind = "picture removed"

	// AnnotationAdded and AnnotationRemoved carry the annotation's subtype — a
	// note, a highlight, a link — and its own text where it has any.
	AnnotationAdded   ChangeKind = "annotation added"
	AnnotationRemoved ChangeKind = "annotation removed"
)

The kinds of change this can see.

type ContentsOptions added in v0.34.0

type ContentsOptions struct {
	// Title is the heading. Empty means "Contents".
	Title string
	// Before is the page the contents goes in front of, counting from one.
	// Zero means the front of the document.
	Before int
	// Size is the type size of an entry, in points. Zero means eleven; the
	// heading is drawn half as large again.
	Size float64
	// Margin is the room left around the text, in points. Zero means 56, which
	// is about two centimetres.
	Margin float64
}

ContentsOptions is how a table of contents is set when it is written as a PAGE of the document rather than as the /Outlines tree a reader navigates by. The zero value is the sensible one.

type DepthError added in v0.33.0

type DepthError struct {
	// Row is which entry, counting from zero.
	Row int
	// Depth is how deep it asked to sit, and Under how deep the entry before it
	// sits.
	Depth, Under int
}

A DepthError is a row sitting more than one level under the row before it, which is a tree with a rung missing: a section heading under nothing, or a sub-section under a sub-section that was never written.

It is a type rather than a sentence so that a caller who knows where its rows came from can say so — ParseOutline reports the line of the file, because the person it answers is looking at a file and not at a slice.

func (*DepthError) Error added in v0.33.0

func (e *DepthError) Error() string

type DeskewOptions added in v0.23.0

type DeskewOptions struct {
	// Threshold is the tilt, in degrees, below which a page is left alone.
	// Zero means half a degree.
	//
	// A page under the threshold comes back untouched rather than turned by a
	// hundredth of a degree: every such turn resamples nothing but costs the
	// page a transformation it did not need, and a scan that is already level
	// should be byte-for-byte the page that came in.
	Threshold float64

	// DPI is how finely each page is drawn before its tilt is measured. Zero
	// means a hundred and fifty, which is BentoPDF's default and which its own
	// documentation calls "fast and accurate for most documents".
	//
	// ⛔ It is a measurement setting only. Nothing of the render reaches the
	// output — see the note above on not rasterising — so a higher DPI buys
	// accuracy and costs time, and never quality.
	DPI float64

	// MaxPixels is passed to the renderer and to the detector, so a media box
	// a file made up cannot be asked to fill memory. Zero leaves each to its
	// own default.
	MaxPixels int
}

DeskewOptions says how to measure and when to act. The zero value is BentoPDF's own default: half a degree, a hundred and fifty DPI.

type Doc

type Doc struct {
	// contains filtered or unexported fields
}

A Doc is a document being assembled: pages in the order they will be written, and the trailer's information dictionary.

func FromDocument

func FromDocument(src *reader.Document) *Doc

FromDocument wraps an already-parsed document. Every page the document reports can be read — the page tree walk has already established that — so there is nothing here that can fail.

func Merge

func Merge(docs ...*Doc) *Doc

Merge joins documents in the order given.

func New

func New() *Doc

New returns an empty document, for merging into.

func Open

func Open(b []byte) (*Doc, error)

Open reads a PDF file held in memory, with the empty password.

func OpenWithPassword

func OpenWithPassword(b []byte, password string) (*Doc, error)

OpenWithPassword reads a PDF file that may be encrypted.

func (*Doc) AddFields added in v0.22.0

func (d *Doc) AddFields(fields ...forms.Field) error

AddFields puts new form fields into the document: the other half of Fill, which can only change a field that is already there.

⛔ IT REFUSES BEFORE THE DOCUMENT IS WRITTEN. forms.CheckAll catches the descriptions that make a file which OPENS and is broken — a field with no name, a choice with no rows, a comb with no MaxLen, two fields of one name — and the page numbers are checked here, where the page count is known.

The fields are held until the write, because a widget names the page object it sits on and the pages do not have numbers until then.

func (*Doc) AddFreeText added in v0.29.0

func (d *Doc) AddFreeText(texts ...FreeText) error

AddFreeText puts text boxes into the document.

⛔ Refused before the write, like AddNotes, and with one check of its own: a box of no width or no height is text nobody will ever see, because the appearance is clipped to it.

func (*Doc) AddInvisibleText added in v0.45.0

func (d *Doc) AddInvisibleText(page int, words []Word) error

AddInvisibleText makes a scanned page searchable: it draws the words over the page in text rendering mode 3, which paints nothing, so the page looks exactly as it did and a viewer can find, select and copy the text.

The design is Tesseract's (src/api/pdfrenderer.cpp, "GlyphLessFont"): ONE Type0 font for the whole file, over a TrueType CIDFont of a single empty glyph, with every code mapped to that glyph, and a ToUnicode CMap that says what each code means. The words are placed by a text matrix and squeezed or stretched to their boxes by horizontal scaling, so no per-language font is ever needed.

The page's own content is left exactly as it is, wrapped in a save and a restore. Apply this LAST: a page that is afterwards tiled onto another by nup, poster or divide is drawn from its own content and loses the words. Calls add to the page; page counts from one.

func (*Doc) AddLayer added in v0.15.0

func (d *Doc) AddLayer(name, parent string) error

AddLayer adds an empty layer, under parent when parent names one.

⛔ The layer has NO CONTENT on it, and that is what adding one means: a template gains a layer for whoever draws on it next. Nothing in the document becomes hidden or shown by adding one.

func (*Doc) AddNotes added in v0.29.0

func (d *Doc) AddNotes(notes ...Note) error

AddNotes puts sticky notes into the document.

⛔ IT REFUSES BEFORE THE DOCUMENT IS WRITTEN, as Mark and AddFields do, and for the same reason: a note on a page the document has not is a mistake the caller can still do something about, while one discovered at the write is a document already half built.

The notes are held until the write, because an annotation names the page OBJECT it sits on and the pages have no object numbers until then.

func (*Doc) AddShapes added in v0.31.0

func (d *Doc) AddShapes(shapes ...Shape) error

AddShapes puts line, rectangle and ellipse annotations into the document.

⛔ Refused before the write, as Mark, AddNotes and AddFreeText are, and for their reason: a caller told at once can draw somewhere else, and one told at Save has already been promised the shape by everything in between.

func (*Doc) Append

func (d *Doc) Append(other *Doc)

Append adds the pages of another document to the end of this one. The other document is not changed, and the two may come from different files.

func (*Doc) Attach added in v0.10.0

func (d *Doc) Attach(name string, data []byte, description string) error

Attach puts a file inside the document, under a name.

The name is what a reader shows and what another tool looks it up by. Two files under one name is a document that has lost one of them, so a name already used is refused rather than quietly replacing what is there.

func (*Doc) Attachments added in v0.10.0

func (d *Doc) Attachments() []Attachment

Attachments are the files the document carries, in the order it names them.

A PDF can hold whole files inside it — the spreadsheet a report was drawn from, the XML a form was filled from, the source of a figure. They are not drawn and nothing on the page says they are there, which is why a tool that rewrites a document can drop them without anyone noticing until the file is wanted.

func (*Doc) Bates

func (d *Doc) Bates(spec, prefix string, start, digits int) error

Bates numbers the pages a range names with a running serial, the way a legal exhibit is marked: a fixed prefix and a zero-padded counter.

func (*Doc) Blank

func (d *Doc) Blank(width, height float64)

Blank adds an empty page of the given size at the end.

func (*Doc) Booklet

func (d *Doc) Booklet() error

Booklet reorders the pages for saddle-stitch printing — folded in half and stapled through the spine — and lays them two to a sheet. Blank pages are added so the count is a multiple of four, which is what folding needs.

func (*Doc) Bytes

func (d *Doc) Bytes() ([]byte, error)

Bytes writes the document out as a PDF file. Every borrowed page is copied out of the file it came from with the attributes it inherited written onto it, so pages from different documents keep their own geometry and resources.

func (*Doc) ClearInfo

func (d *Doc) ClearInfo()

ClearInfo drops the whole information dictionary, which is what "remove the metadata" means.

func (*Doc) Compress added in v0.2.0

func (d *Doc) Compress()

Compress asks for the file to be written with its objects packed into compressed streams and a cross-reference stream, which is what every writer since PDF 1.5 does and what makes a file a good deal smaller. It costs nothing but a version of 1.5, which every reader in use has understood for twenty years.

func (*Doc) ContentsPage added in v0.34.0

func (d *Doc) ContentsPage(marks []Bookmark, opt ContentsOptions) (int, error)

ContentsPage writes the entries as a table of contents PAGE — the printed kind, with a page number at the right of each line and dots leading to it — and returns how many pages it added.

⛔ THE NUMBERS IT PRINTS ARE MOVED BY THE PAGES IT ADDS. A contents page put in front of a document pushes every page of it down, so an entry that pointed at page 7 before is on page 8 after, and printing the 7 would send a reader one page short of every heading in the book. That is done here, once, from what this function itself inserted — and ShiftBookmarks is the same rule for a caller that is also writing the /Outlines tree from the same entries:

n, err := doc.ContentsPage(marks, ops.ContentsOptions{})
doc.SetOutline(ops.ShiftBookmarks(marks, 1, n))

⛔ AND IT RUNS ONTO AS MANY PAGES AS IT NEEDS. A table of contents quietly missing its last nine entries is worse than one that refuses to be written: the first is a document that looks finished.

func (*Doc) Crop

func (d *Doc) Crop(spec string, box [4]float64) error

Crop sets the visible area of the pages the range names, in points, as [left bottom right top]. It sets the crop box; the media box, which is the paper the page is on, is left alone.

func (*Doc) Decrypt added in v0.2.0

func (d *Doc) Decrypt()

Decrypt writes the file without protection. A document opened with the right password is already decrypted, so this only undoes an earlier call to Doc.Encrypt; a file read with OpenWithPassword and written out is unprotected either way.

func (*Doc) Delete

func (d *Doc) Delete(spec string) error

Delete removes the pages the range names.

func (*Doc) Deskew added in v0.23.0

func (d *Doc) Deskew(opt DeskewOptions) ([]PageSkew, error)

Deskew measures every page and turns the ones tilted by more than the threshold, reporting what it found page by page.

The page keeps its size, so the corners of the turned content move outside the media box and are clipped. That is what straightening a scan means — the paper is the same paper — and on a scan it costs nothing, because the text block sits well inside the margins. It is the same thing BentoPDF's does.

func (*Doc) Detach added in v0.10.0

func (d *Doc) Detach(name string) bool

Detach removes the file of that name, and says whether there was one.

func (*Doc) Divide added in v0.15.0

func (d *Doc) Divide(across, down int) error

Divide cuts each page into an across×down grid of smaller pages, each the size of the piece it holds.

It is for a page that holds things which should have been separate: a two-page spread scanned as one wide sheet, two tickets printed side by side, a sheet of labels. Dividing a wide spread down the middle with Divide(2, 1) gives two pages of half the width, each of them the page it was before somebody put two on a sheet.

⛔ This is NOT Doc.Poster, although the grid is the same. Poster keeps every sheet the size of the page it came from, which means it ENLARGES: the pieces printed and taped together make one page the size of a wall. Divide keeps the content at its own size and makes the pages smaller, so the pieces laid side by side are the page again at 1:1. Confusing the two gives a result that looks right in a thumbnail and is wrong by a factor of across and down — which is why the distinction is in both doc comments rather than left to whoever reads the grid arguments.

The pieces come out in reading order: left to right, top to bottom, the top-left one first.

The cuts meet exactly. Nothing is repeated from one piece to the next and no bleed is left, because Divide is told how many pieces to make and not what a trimmer needs; every part of the page lands on one piece and one only, so the pieces are exactly the page again.

func (*Doc) DropBlank added in v0.15.0

func (d *Doc) DropBlank(opt BlankOptions) ([]int, error)

DropBlank removes the pages that hold almost nothing and reports which went, numbered as they were BEFORE the removal — because a caller who wants to say what happened needs the numbers the reader saw.

⛔ It refuses to empty the document. A file of no pages is still a file: it opens, it has a size, and a caller who handed over a stack of scans that turned out to be blank would be told nothing was wrong while being given something no reader can show. Every page blank is a result worth an error.

func (*Doc) DropLayer added in v0.15.0

func (d *Doc) DropLayer(name string) error

DropLayer removes a layer.

⛔ WHAT WAS DRAWN ON IT DOES NOT GO WITH IT. The content stays in the page and stops being optional, so a HIDDEN layer that is dropped becomes permanently visible — which is the opposite of what somebody deleting a layer called "internal pricing" expects. Removing the content as well would mean rewriting every content stream that mentions the layer, which this does not do; the refusal below is the honest half of that.

func (*Doc) DropOutlines

func (d *Doc) DropOutlines()

DropOutlines leaves the bookmarks behind. They are kept by default: a merge that loses every bookmark is a poor merge.

func (*Doc) DuplexCollate added in v0.15.0

func (d *Doc) DuplexCollate(split int, reverseBacks bool) error

DuplexCollate puts a duplex stack back in reading order.

An automatic feeder that cannot turn a sheet over leaves ONE file holding two blocks: every front, then every back. This cuts it at split and interleaves the two halves, so front1, back1, front2, back2 and on.

A split of zero or less means the middle, rounded UP — ceil(n/2) — because an odd stack has the unpaired sheet at the END of the fronts, not the start of the backs. Thirteen pages split at seven, not six.

⛔ reverseBacks is not a convenience, it is the common case: the stack is turned over AS A STACK, so the last sheet's back is scanned first. Without it a thirty-sheet batch comes out with every back on the wrong front, which is a defect that reads as "the scan is fine, the order is odd" rather than as a reversal.

Blocks of different sizes do not stop it: the pairs collate first and whatever is left over follows in order, which is what the last single-sided sheet of a batch leaves behind.

func (*Doc) Encrypt added in v0.2.0

func (d *Doc) Encrypt(e reader.Encryption)

Encrypt protects the file that will be written. Two people can open it: whoever knows the user password, subject to the permissions, and whoever knows the owner password, subject to nothing.

An encrypted file is not byte-for-byte reproducible — encryption needs randomness, by design — so a document written twice with the same call comes out different both times, and neither can be compared with the other.

func (*Doc) Flatten

func (d *Doc) Flatten()

Flatten draws each annotation's own appearance into the page and then drops the annotation, so what one reader sees is what every reader sees — which is what filling in a form and then flattening it means.

func (*Doc) Info

func (d *Doc) Info() reader.Dict

Info returns the document information dictionary, which may be nil.

func (*Doc) InsertBlank

func (d *Doc) InsertBlank(i int) error

InsertBlank puts an empty page before the page at i, counting from one; an index one past the end appends. The size is taken from the page it precedes, or from the one before it at the end of the document.

func (*Doc) Interleave added in v0.9.0

func (d *Doc) Interleave(others ...*Doc) error

Interleave takes pages from each document in turn — the first of this, the first of the next, and round again — until every one of them is used up.

It is what a duplex scanner leaves behind. A stack fed through a single-sided feeder twice comes out as two files: the fronts in order, and the backs, which is the same document taken apart. Merging them end to end gives every front then every back; this gives the document.

The backs are usually in reverse: the stack is turned over as a stack, so the last sheet's back is scanned first. Reverse that one before interleaving and the pages land in the right order.

Documents of different lengths do not stop it. A shorter one simply runs out, and the rest of the longer one follows in order — which is what a scanner leaves when the last sheet is single-sided.

func (*Doc) Layers added in v0.15.0

func (d *Doc) Layers() []Layer

Layers reports the document's layers, in the order the document asks them to be shown and with their nesting.

A document with no optional content has none.

func (d *Doc) Links() []Link

Links is every link annotation of the document, in page order and, within a page, in the order the page lists them.

It reads the files the pages came from: a link added by this package's own verbs is not among them, because none of them adds one.

/A with /S /GoTo    a page of this document
/A with /S /URI     an address
/Dest               a page of this document, through a name or a name tree

⛔ /A IS READ FIRST. A link is not meant to carry both /A and /Dest — the link-annotation clause of the PDF specification (ISO 32000-1 §12.5.6.5, Table 173) makes /Dest "not permitted if an A entry is present", as three independent implementations' documentation records; the clause's own wording was not opened here. A file carrying both is therefore malformed, and the action is what a reader acts on, so it is what this reports.

Everything else — GoToR into another file, Launch, Named, JavaScript, a chain of /Next actions — is a link this does not follow. It is still listed.

func (*Doc) Mark added in v0.26.0

func (d *Doc) Mark(marks ...Markup) error

Mark puts text markup annotations into the document.

⛔ IT REFUSES BEFORE THE DOCUMENT IS WRITTEN, as AddFields does: a mark on a page the document has not, or with no quadrilaterals, is a mistake the caller can still do something about. QuadPoints is REQUIRED by Table 179, so a markup with none is not an annotation with something missing — it is one that marks nothing.

The marks are held until the write, because an annotation names the page object it sits on and the pages have no objects until then.

func (*Doc) Move

func (d *Doc) Move(from, to int) error

Move takes the page at from and puts it at to, both counting from one, the other pages closing up behind it.

func (*Doc) NUp

func (d *Doc) NUp(n int) error

NUp lays n pages on each sheet, in reading order. The sheet keeps the size of the first page, and the grid is whichever arrangement of at least n cells gives cells closest in shape to the pages going into them.

func (*Doc) OnePage added in v0.9.0

func (d *Doc) OnePage() error

OnePage puts every page on a single sheet, one below the other.

A page is a unit of paper, not a unit of reading: a receipt, a chat log and a web page cut into A4 are one thing that a printer divided. This puts them back, so what is read scrolls rather than turns.

The sheet is as wide as the widest page and as tall as all of them stacked. Pages narrower than the widest are centred, because a column of text that jumps from side to side is harder to read than one that does not.

func (*Doc) OutlineSkipped added in v0.43.0

func (d *Doc) OutlineSkipped() int

OutlineSkipped is how many annotations of the pages last written carry a font in their appearance and so still hold text after Doc.OutlineText.

func (*Doc) OutlineText added in v0.43.0

func (d *Doc) OutlineText(spec string) error

OutlineText writes the text of the pages a range names as paths, so that the page looks as it did and no longer holds a font: nothing is left to select, search, or be missing on a machine that lacks the font.

The glyphs are the ones go-pdfkit/render draws, so a page looks after what the renderer showed before. What is carried over, and what is not:

  • TrueType, CFF and Type 1 fonts, embedded or standing in for one of the fourteen, become filled paths (render mode 0), stroked ones (1), both (2), or nothing (3); modes 4 to 7 add the glyphs to the clip at the end of the text object. A stand-in for a bold face is filled and not thickened.
  • A Type 3 glyph becomes a Form XObject of its own, drawn where the glyph was. A glyph that only sets a shape (d1) takes the colour of the text.
  • Text in a Form XObject or a tiling pattern is outlined too, in a copy: the original is shared with pages that were not named and stays as it was.
  • A font written vertically makes the write fail with ErrOutlineVertical, and a page past the bounds with ErrOutlineTooLarge.

⛔ What is NOT reached: the appearance streams of annotations (counted by Doc.OutlineSkipped), text added to the document afterwards by a stamp, and the text state a form inherits from the page that draws it. The fonts of the interactive form's default resources are left in the catalogue. A page cannot be both outlined and recoloured, redacted or have its text replaced.

func (*Doc) Overlay

func (d *Doc) Overlay(other *Doc) error

Overlay draws each page of another document on top of the pages here, in order. When the other document has fewer pages its last page is not repeated: pages past its end are left alone.

func (*Doc) PageBox added in v0.45.0

func (d *Doc) PageBox(page int) ([4]float64, error)

PageBox is the area of a page a viewer shows, in the page's own user space: left, bottom, right, top. It is what a recogniser's pixel coordinates are to be scaled onto. Page counts from one.

func (*Doc) PageCount

func (d *Doc) PageCount() int

PageCount reports how many pages the document has.

func (*Doc) PageLabels added in v0.15.0

func (d *Doc) PageLabels() []string

PageLabels reports what each page of the document is labelled, in order, as a viewer would show it. A page with no label comes back as "".

It answers for the document as it stands: the labels a caller set, or the ones carried over from the files the pages came from.

func (*Doc) PageNumbers

func (d *Doc) PageNumbers(spec, format string) error

PageNumbers writes a number at the foot of the pages a range names. The format is a stamp's text, so "{page} of {pages}" and "— {page} —" both work.

func (*Doc) Picture added in v0.8.0

func (d *Doc) Picture(data []byte, dpi float64) error

Picture adds a page holding one image, the size of the image.

This is the other half of drawing a page: a scanner, a camera and a screenshot all produce a picture, and what people want of a PDF toolkit is to be handed one back with the picture in it.

Every format go-gfx/gfx reads is accepted, which is more than a PDF can carry. A JPEG is put in as it stands, because a PDF carries JPEG and re-encoding one loses a little of it for nothing; everything else is decoded and written as samples, compressed. An image with any transparency in it gets a soft mask, so a PNG drawn over the page's white does not come out with black behind it.

dpi says how many of the image's pixels go into an inch of paper; 0 means 72, one point per pixel. A photograph from a telephone at 72 is a page the size of a wall, and at 300 it is a photograph.

func (*Doc) Place added in v0.21.0

func (d *Doc) Place(spec string, p Placement) error

Place draws a picture on the pages a range names.

⛔ The drawing itself was already here and reachable by nothing: the machinery that puts an image at a rectangle on a page (placedPicture, placedContent) was written for the XFA renderer and only XFA fed it, so a capability the package HAD could not be asked for. A borrowed page did not even honour it — the conditions that decide whether a source page is wrapped or cached counted marks and not pictures — which is the shape a capability takes when it exists and is not wired: present, tested through one caller, and absent from the outside.

What it serves, beyond a logo: a drawn or typed signature placed on a page, which is what every "sign a PDF" tool means by signing — a picture, not cryptography. The cryptographic kind is a different job with a different name, and conflating the two is how a drawn squiggle gets called a digital signature.

func (*Doc) Poster added in v0.11.0

func (d *Doc) Poster(across, down int) error

Poster spreads each page over across×down sheets, so that the sheets printed and taped edge to edge make one page the size of a wall. It is the inverse of Doc.NUp, which puts several pages on one sheet.

Every sheet is the size of the page it came from. A poster of an A4 document therefore prints on A4, and each piece has the page's own proportions — pieces of some other shape do not tape back into the page they were cut from. Because the sheets keep their shape, a wall of them is only the page's shape again when across and down are equal; otherwise the page is enlarged as far as it will go inside the wall and centred, and the sheets at the edges carry the white that is left over.

The sheets meet exactly: nothing is repeated from one to the next, and no margin is left for taping. An overlap would have to be a constant here, because Poster is told how many sheets to use and not how wide the printer's unprinted border is; too small a guess still leaves a seam, too large a one loses more of the poster to trimming than it saves, and neither could be turned off. Meeting exactly is also the only arrangement that is exactly undone: every part of the page lands on one sheet and one only, so the pieces butt together — taped from behind — with nothing to cut away and nothing printed twice.

The sheets come out in reading order: left to right, top to bottom, the top-left one first, so a printed pile can be laid out on a table in the order it came off the printer.

func (*Doc) Protection added in v0.2.0

func (d *Doc) Protection() (reader.Protection, bool)

Protection reports how the file this document was read from was protected, and false when it was not protected at all — or when the document was not read from a file. It says nothing about how the document will be written: that is what was passed to Doc.Encrypt.

func (*Doc) RecolourText added in v0.16.0

func (d *Doc) RecolourText(spec string, r, g, b float64) error

RecolourText paints the text of the pages a range names in one colour, leaving everything else on the page as it was.

The colour is red, green and blue, each from zero to one.

⛔ It reaches the text in each PAGE'S OWN content stream. Text drawn through a Form XObject is NOT recoloured, and the reason is not that it would be hard: an XObject is SHARED, so recolouring one would change pages the caller did not name. Doc.RecolourText therefore counts what it could not reach and Doc.UnreachedText reports it — because a tool that silently did nothing to a document whose text is all in XObjects would be worse than one that refused.

func (*Doc) Redact added in v0.28.0

func (d *Doc) Redact(rs ...Redaction) error

Redact removes the text inside each region and paints the region over.

⛔ IT REFUSES RATHER THAN HALF-REDACTS. A redaction that removed some of what it was asked to remove, and said nothing about the rest, would be worse than no redaction at all: the caller would believe the document safe to send. So this returns an error, naming the page and the reason, when a region holds anything it cannot take out:

  • text inside a Form XObject. Its bytes are not this page's, and an XObject is SHARED — editing it to clean one page would change every page that draws it. Doc.RecolourText stops at the same wall, and counts what it could not reach for the same reason.

  • an image it cannot write back. The spec is explicit that a mask or a clip will not do and the pixels themselves must be destroyed, so a picture whose samples this cannot rewrite is a refusal naming the reason: a turned or skewed placement, a picture the page draws more than once, a stencil or a soft mask, a palette, more or fewer than eight bits a sample, a colour space this does not know. Plain samples and JPEGs are blanked.

    ⛔ A JPEG IS WRITTEN BACK AS PLAIN SAMPLES, not as another JPEG. Re-encoding re-quantises every block of the picture, including the ones nobody asked about, so a redaction would visibly degrade the rest of the page; what this writes instead is exactly what a reader of the original would have seen, with the region destroyed. The picture loses its compression and the file grows — a photograph as Flate is several times the same photograph as a JPEG — which is the trade, and the caller's to know about.

  • an annotation. Its /Contents can hold the very words being redacted.

  • a text-showing operator only PART of whose text is inside the region. Blanking it would take away text the caller did not ask about, and rewriting it cannot be done by re-emitting the surviving words: the bytes in the stream are font codes, and Unicode does not round-trip back to them through a CID font's map. Keeping the surviving pieces' original bytes and replacing the removed ones with an equivalent kern is the way, and it is not in this release.

What it does remove it removes from the bytes: the operator is overwritten with spaces, so the string is gone from the content stream rather than hidden.

func (*Doc) RemoveAnnotations

func (d *Doc) RemoveAnnotations()

RemoveAnnotations drops every annotation: links, comments, form fields and all. What was drawn on the page stays; what sat on top of it goes.

func (*Doc) Repaired added in v0.15.0

func (d *Doc) Repaired() bool

Repaired says whether any file this document's pages came from had to be rebuilt before it could be read: a cross-reference table that did not match the objects, a trailer that was not there, an offset that pointed into the middle of something else.

reader does the rebuilding on its own, and quietly, which is the right behaviour for a reader — a caller asking for page three wants page three, not a lecture. But it leaves nobody able to SAY it happened, and that is worth saying for two different reasons: a file that needed rebuilding should be written back out and kept in its rebuilt form, and a file that did not need it should not be presented as rescued.

⛔ ANY, not all. A merged document's pages come from several files, and one damaged source is the answer to "did this need repairing": a true that depended on every source being broken would be false for every real merge.

func (*Doc) ReplaceText added in v0.30.0

func (d *Doc) ReplaceText(edits ...TextEdit) error

ReplaceText rewrites the text of operations the caller names.

What it refuses, each with the page and the words at issue:

  • a run drawn from inside a Form XObject, whose span does not index the page's own stream and which is SHARED with every other page that draws it. Doc.Redact and Doc.RecolourText stop at the same wall.
  • an operation that draws more text than the run being replaced — a TJ array of several strings. Rewriting the whole of it would re-draw the others from Unicode, and Unicode does not round-trip back to font codes.
  • the operators ' and ", which also move to the next line and set the word and character spacing. Re-emitting them as a TJ array would lose those effects, and the page would re-flow around an edit that looked local.
  • a composite (CID) font, where the bytes of the string are codes a CMap defines and nothing can invert. A simple font's encoding CAN be walked code by code, which is what makes the rest of this possible.
  • a character the page's own font cannot draw. The replacement has to be written in the codes that font understands; a rune it has no code for would come out as a blank or as the wrong glyph.
  • a replacement with a different number of spaces, because word spacing (Tw) adds a displacement per space character that this cannot see from the stream alone. Same count, same Tw, same answer.

func (*Doc) Resize

func (d *Doc) Resize(spec string, box [4]float64) error

Resize sets the media box — the paper — of the pages the range names.

func (*Doc) Reverse

func (d *Doc) Reverse()

Reverse puts the pages in the opposite order.

func (*Doc) Rotate

func (d *Doc) Rotate(spec string, degrees int) error

Rotate turns the pages the range names by the given number of degrees, which must be a multiple of ninety. The rotation is relative to what the page already had, so rotating twice by ninety turns a page upside down.

func (*Doc) Rotation

func (d *Doc) Rotation(i int) (int, error)

Rotation reports the rotation of the i'th page, counting from one.

func (*Doc) Sanitize

func (d *Doc) Sanitize()

Sanitize strips the parts of a file that do something rather than show something: page and annotation actions, JavaScript, launching, form submission, files travelling with a page, and the annotation types that exist to embed or play something.

A document written by this package always carries a catalogue of this package's own making, so document-level scripts, automatic actions on opening and embedded file trees are gone whatever this setting says; sanitising deals with what travels attached to a page.

func (*Doc) Select

func (d *Doc) Select(spec string) error

Select keeps only the pages the range names, in the order it names them, so it extracts, reorders and duplicates in one verb.

func (*Doc) SetInfo

func (d *Doc) SetInfo(key reader.Name, value string)

SetInfo replaces one entry of the information dictionary. An empty value removes it.

func (*Doc) SetLayerVisible added in v0.15.0

func (d *Doc) SetLayerVisible(name string, visible bool) error

SetLayerVisible turns a layer on or off.

⛔ A LOCKED layer is refused. The lock is the document asking that this one not be switched — a drawing's dimension layer that everything else is positioned against — and a tool that switched it anyway would be ignoring the only thing the file says about its own layers.

func (*Doc) SetMaxPixels added in v0.24.0

func (d *Doc) SetMaxPixels(n int)

SetMaxPixels sets the largest picture, as width times height, that Doc.Picture and Doc.Place will decode. Zero, the default, means codec.DefaultMaxPixels (40 million: a 40 megapixel image); a negative value is treated as zero.

⛔ The number the ceiling guards comes from the FILE: a compressed format describes a large image in a few bytes, so a PNG declaring 100000 by 100000 is tens of kilobytes and tens of gigabytes once decoded. A 50 megapixel camera photo is refused by the default; a caller who takes photographs from people they trust can raise it here, and one taking files from strangers should lower it to what they actually need. A picture above the ceiling is refused with an error for which errors.Is(err, codec.ErrTooLarge) holds.

func (*Doc) SetOutline added in v0.4.0

func (d *Doc) SetOutline(marks []Bookmark)

SetOutline writes these bookmarks rather than carrying over the ones the sources had. An entry pointing at a page this document has not got is left out, and so is everything under it: a heading whose section has gone is not a heading any more.

Passing nothing puts the sources' own bookmarks back.

func (*Doc) SetPageLabels added in v0.15.0

func (d *Doc) SetPageLabels(rules []LabelRule) error

SetPageLabels replaces the document's page labels.

The rules are applied in order, so a later rule wins where two overlap. A page no rule names has no label, and a viewer then shows its position in the file — which is the right answer and is what an unlabelled document does.

Passing no rules removes the labels.

func (*Doc) SetRotation

func (d *Doc) SetRotation(spec string, degrees int) error

SetRotation turns the pages the range names to an absolute angle.

func (*Doc) SetVersion

func (d *Doc) SetVersion(v string)

SetVersion sets the version written in the header.

func (*Doc) Split

func (d *Doc) Split(n int) ([]*Doc, error)

Split cuts the document into pieces of at most n pages each.

func (*Doc) SplitAt

func (d *Doc) SplitAt(at ...int) ([]*Doc, error)

SplitAt cuts the document before each of the given page numbers, which is how a report is broken into chapters.

func (*Doc) Stamp

func (d *Doc) Stamp(spec string, s Stamp) error

Stamp draws text on the pages a range names.

func (*Doc) Turn added in v0.36.0

func (d *Doc) Turn(spec string, degrees float64) error

Turn turns the pages the range names by an arbitrary angle in degrees, clockwise, adding to whatever rotation they already carry. The sheet grows to hold the turned page, so no corner is cut off.

An angle that is a multiple of ninety is written as the page's own /Rotate and nothing else happens: no transformation, no new content stream, and a page whose text was selectable stays selectable. That is both cheaper and more faithful than turning it by a matrix, and it is what the reference does too.

func (*Doc) Underlay

func (d *Doc) Underlay(other *Doc) error

Underlay draws each page of another document underneath the pages here.

func (*Doc) UnreachedText added in v0.16.0

func (d *Doc) UnreachedText() int

UnreachedText reports how many text-showing operations the last write left in a colour of their own because they are inside a Form XObject, which is shared and so cannot be recoloured for one page without changing others.

It is zero until the document has been written, because until then there is nothing to have reached.

func (*Doc) Version

func (d *Doc) Version() string

Version reports the PDF version that will be written.

func (*Doc) Watermark

func (d *Doc) Watermark(spec, text string) error

Watermark draws large, pale, slanted text across the pages a range names — the thing the word usually means.

type Filling added in v0.5.0

type Filling struct {
	// contains filtered or unexported fields
}

A Filling is a document's form, opened so that it can be filled in and written back.

func OpenForm added in v0.5.0

func OpenForm(b []byte) (*Filling, bool, error)

OpenForm reads a document's form. It reports false, with no error, for a document that simply has none — including one carrying an AcroForm dictionary a producer left behind with an empty field list, which 561 of the figure corpus's 118 833 files do.

func OpenFormWithPassword added in v0.5.0

func OpenFormWithPassword(b []byte, password string) (*Filling, bool, error)

OpenFormWithPassword is the same for a document that is protected.

func (*Filling) Bytes added in v0.5.0

func (f *Filling) Bytes() ([]byte, error)

Bytes writes the original file with the changes appended to it.

func (*Filling) Fill added in v0.5.0

func (f *Filling) Fill(name, value string) error

Fill sets one field by name, which is what a command line or a map of answers wants.

func (*Filling) Form added in v0.5.0

func (f *Filling) Form() *forms.Form

Form is what was read, to be asked about its fields and told what they hold.

type Font

type Font string

A Font names one of the four faces this package can draw with.

const (
	Helvetica     Font = "Helvetica"
	HelveticaBold Font = "Helvetica-Bold"
	Courier       Font = "Courier"
	CourierBold   Font = "Courier-Bold"
)

The faces available. Any other name reads as Helvetica.

func (Font) Width

func (f Font) Width(s string, size float64) float64

Width reports how wide a string is at the given point size, once encoded.

type FreeText added in v0.29.0

type FreeText struct {
	// Page is 1-based.
	Page int
	// X0, Y0, X1, Y1 are the box, in the page's own points.
	X0, Y0, X1, Y1 float64
	// Text is what it says. Lines are wrapped to the box's width; a \n starts a
	// new line.
	Text string
	// Font and Size are the face and the point size; the zero values are
	// Helvetica at 12.
	Font Font
	Size float64
	// Align is the justification.
	Align Quadding
	// Author is /T.
	Author string
	// R, G, B are the TEXT's colour in 0..1, black by default — which is what a
	// typewriter comment is, and the one case where the zero value is right.
	R, G, B float64
}

A FreeText is text shown directly on the page, in a box.

type LabelRule added in v0.15.0

type LabelRule struct {
	// Pages is a range in this package's usual form: "1-4", "7", "odd",
	// "1-9,30-40". Empty means every page.
	Pages string
	// Style is how the number is written. The zero value writes no number,
	// which is [LabelNone] and is a style rather than an omission.
	Style LabelStyle
	// Prefix goes before the number: "A-" makes A-1, A-2, A-3.
	Prefix string
	// Start is the value of the first label in the range. Zero means one.
	//
	// ⛔ It must be at least one, and that is the FORMAT's rule rather than a
	// choice here: ISO 32000-1 table 159 says /St "shall be greater than or
	// equal to 1". A zero-based numbering scheme cannot be written as a
	// numeric style at all, so Start of less than one is refused rather than
	// written out of specification — a file that opens in one viewer and
	// renumbers itself in another is worse than a refusal.
	Start int
	// Continue carries the numbering across the pieces of a DISJOINT range.
	//
	// ⛔ A page-label range in a PDF is CONTIGUOUS: the file holds the first
	// page of each run and the viewer counts forward from there, so a rule
	// over "1-9,30-40" has to become two runs. Without Continue the second
	// run starts again at Start; with it, it carries on from where the first
	// left off. "odd" over a hundred pages is fifty runs of one page, and
	// both answers are expressible only because the rule is compiled into
	// runs rather than stored as written.
	Continue bool
}

A LabelRule labels the pages a range names.

Page labels are what a VIEWER shows in its toolbar — "iv of 320" — and never what is printed on the paper. For a number on the page, see Doc.PageNumbers.

type LabelStyle added in v0.15.0

type LabelStyle string

A LabelStyle is how the numeric part of a page label is written. They are the format's own one-letter names, so that what goes in the file is what the caller asked for.

const (
	LabelDecimal      LabelStyle = "D" // 1, 2, 3
	LabelLowerRoman   LabelStyle = "r" // i, ii, iii
	LabelUpperRoman   LabelStyle = "R" // I, II, III
	LabelLowerLetters LabelStyle = "a" // a, b, c … z, aa, bb
	LabelUpperLetters LabelStyle = "A" // A, B, C … Z, AA, BB
	// LabelNone writes no number at all: the label is the prefix alone, which
	// is how a run of pages is marked "Cover" or "Insert".
	LabelNone LabelStyle = ""
)

type Layer added in v0.15.0

type Layer struct {
	// Name is what the viewer shows. ⛔ It is NOT unique: a document may hold
	// two layers of the same name, and the methods here say so rather than
	// guessing which was meant.
	Name string
	// Visible is whether the document's default configuration has it on.
	Visible bool
	// Locked is whether the document asks that it not be switched: a viewer
	// shows the layer greyed, and [Doc.SetLayerVisible] refuses it.
	Locked bool
	// Depth is how deeply the layer is nested in the document's order, from
	// zero. A drawing groups its layers, and the nesting is what makes a list
	// of forty of them readable.
	Depth int
}

A Layer is one of a document's optional content groups — what a viewer calls a layer, and what a drawing keeps its dimensions, its markup and its alternatives on.

type Level added in v0.33.0

type Level struct {
	Title string
	Page  int
	// Depth is zero for a top-level entry and one more for each level of
	// nesting under it.
	Depth int
}

A Level is one entry of a table of contents in reading order, carrying how deep it sits rather than what sits under it.

It is what a reader of a table of contents has BEFORE it has a tree: a text file's indentation, or the /Outlines tree of a document already open, walked in reading order. Nest turns a run of them into the Bookmarks SetOutline takes.

func Flatten added in v0.34.0

func Flatten(marks []Bookmark) []Level

Flatten is a bookmark tree read in reading order, each entry carrying how deep it sits rather than what sits under it: the inverse of Nest, and what a printed contents needs for its indentation.

type Link struct {
	Page   int
	Rect   [4]float64
	Target int
	URI    string
}

A Link is one link annotation of the document as it now stands: where it sits, and where it leads.

Page and Target are numbered in THIS document, not in the files its pages came from, so a link survives having its pages reordered and reports Target 0 once the page it pointed at has been dropped.

Rect is in PDF user space — origin bottom-left, y upwards — and normalised so that Rect[0] <= Rect[2] and Rect[1] <= Rect[3]. A file is free to write a rectangle from either pair of corners, and a caller hit-testing an un-normalised one finds nothing at all, which looks exactly like a page with no links on it.

func (Link) Leads added in v0.25.0

func (l Link) Leads() bool

Leads reports whether this link goes somewhere that can be named: a page of this document, or an address.

⛔ A link that leads NOWHERE THIS CAN FOLLOW is still in the list, with Target 0 and URI "". Dropping it would have a caller counting links under-report, and "twelve links, one of which goes somewhere I cannot follow" is a different fact from "eleven links". It happens for an honest reason as well as a dishonest one: a page this document no longer has, a GoToR into another file, a Launch, a destination name nothing defines.

type Markup added in v0.26.0

type Markup struct {
	// Page is 1-based.
	Page int
	// Kind is which mark to make; the zero value is a highlight.
	Kind MarkupKind
	// Quads are the pieces of text to mark, one per line — "each quadrilateral
	// shall encompass a word or group of contiguous words" (Table 179).
	Quads []Quad
	// R, G, B are the mark's colour in 0..1. The zero value is the yellow a
	// highlighter is, rather than black, which would hide the words.
	R, G, B float64
	// Author and Note are what the mark says about itself: /T and /Contents.
	// Both may be empty.
	Author, Note string
}

A Markup is one mark over a stretch of a page's text.

type MarkupKind added in v0.26.0

type MarkupKind uint8

A MarkupKind is which mark to make.

const (
	MarkHighlight MarkupKind = iota
	MarkUnderline
	MarkStrikeOut
	MarkSquiggly
)

type Note added in v0.29.0

type Note struct {
	// Page is 1-based.
	Page int
	// X and Y are where the icon's bottom left corner goes, in the page's own
	// points. The icon is noteSide points square.
	X, Y float64
	// Author and Contents are /T and what the note says. Contents is required:
	// a note that says nothing is an icon in the margin with nothing behind it.
	Author, Contents string
	// Open asks for the pop-up to be showing when the document is opened.
	Open bool
	// Icon is which of Table 172's seven to name; empty means Note.
	Icon NoteIcon
	// R, G, B are the icon's colour in 0..1. The zero value is the yellow a
	// sticky note is.
	R, G, B float64
}

A Note is a sticky note attached to a point on a page.

type NoteIcon added in v0.29.0

type NoteIcon string

A NoteIcon is the icon a closed note shows.

⛔ The seven Table 172 requires a reader to provide, and no others. The table says "additional names may be supported as well", which means a name outside this list is a note that may show up as nothing in a reader that does not know it. Since the appearance we write decides what it looks like anyway, the value of the /Name entry is fidelity to the format, and an invented one buys nothing and risks a blank.

const (
	IconNote         NoteIcon = "Note"
	IconComment      NoteIcon = "Comment"
	IconKey          NoteIcon = "Key"
	IconHelp         NoteIcon = "Help"
	IconParagraph    NoteIcon = "Paragraph"
	IconNewParagraph NoteIcon = "NewParagraph"
	IconInsert       NoteIcon = "Insert"
)

type Page

type Page struct {
	// contains filtered or unexported fields
}

A Page is one page of a document, borrowed from the file it came from. The rotation is what will be written, not what the source said.

type PagePair added in v0.37.0

type PagePair struct {
	Before, After int
	Changes       []Change
}

A PagePair is one page of the earlier document set beside the page of the later one that answers to it, and everything that differs between them.

Before and After are page numbers counting from one. One of them is zero when the pairing found no partner: a page only the later document has is {Before: 0, After: n}.

func Compare added in v0.37.0

func Compare(before, after []byte) ([]PagePair, error)

Compare says what changed between two documents, page by page.

The pages are paired by how much text they share rather than by their numbers, so a page inserted in the middle moves nothing after it: the pages that follow are still paired with the pages they came from, and the insertion is one PageAdded.

func (PagePair) Changed added in v0.37.0

func (p PagePair) Changed() bool

Changed reports whether anything at all differs on this pair.

type PageSkew added in v0.23.0

type PageSkew struct {
	Page int
	// Angle is the tilt found, in degrees, positive counter-clockwise. It is
	// reported whether or not the page was corrected, because "measured and
	// left alone" is a different answer from "not measured".
	Angle float64
	// Corrected says whether the page was turned.
	Corrected bool
	// Err is why this page could not be measured, and is nil otherwise. A page
	// with nothing on it has no skew, and one page that cannot be measured is
	// no reason to refuse the other three hundred.
	Err error
}

A PageSkew is what was found on one page, numbered from one.

func SkewAngles added in v0.23.0

func SkewAngles(pdf []byte, opt DeskewOptions) ([]PageSkew, error)

SkewAngles measures the tilt of every page of a file, in order, numbered from one.

⛔ A page that cannot be measured is REPORTED, not fatal. A blank separator sheet in the middle of a stack of scans has no skew — there is nothing on it to be tilted — and refusing the whole document over it would be refusing to deskew a stack of scans because one page was blank. The reason lands in PageSkew.Err, so a caller can say what happened per page.

type Placement added in v0.21.0

type Placement struct {
	// Data is the picture, in any format go-gfx/gfx reads — which is more
	// than a PDF can carry, and more than this package needs to care about:
	// a JPEG goes in as it stands and everything else is decoded and
	// recompressed, exactly as [Doc.Picture] does it.
	Data []byte

	// Position says which of the nine places on the page it goes, and Margin
	// how far from the edge, in points; zero means 24, as a stamp's does.
	Position Position
	Margin   float64

	// At, when Anchored is true, is the bottom left corner in the page's own
	// points, and Position is then ignored.
	//
	// ⛔ A separate flag rather than "At is zero means unset": the bottom left
	// corner of a page IS (0,0), and a caller placing a signature in the
	// corner of a scanned form would silently get it centred.
	At       [2]float64
	Anchored bool

	// Width and Height are the size on the page, in points. Giving one of
	// them keeps the picture's own proportions; giving both may distort it,
	// which is the caller's business and not this package's.
	Width, Height float64

	// DPI sizes it from its own pixels instead: 300 means a 300-pixel-wide
	// picture is an inch across. Zero means 72, one point per pixel, which is
	// what [Doc.Picture] means by it too.
	//
	// It is ignored when Width or Height is given.
	DPI float64

	// Opacity means exactly what [Stamp.Opacity] means: the alpha the picture
	// is drawn with, where zero is the unset default and therefore fully
	// opaque, and 0.25 is pale.
	//
	// ⛔ The first version of this field was the other way round — "how much
	// of the page shows through" — which would have put TWO meanings of one
	// word in one package: a watermark at 0.25 is pale and a placement at
	// 0.25 would have been nearly solid. Nothing would have failed; the
	// picture would simply have come out wrong for everyone who read the
	// other field first.
	Opacity float64
}

A Placement is a picture drawn at a place on a page: a signature, a logo, a stamp that is an image rather than a line of text.

⛔ Its shape deliberately mirrors Stamp's, because the two answer the same question about a page and a reader of one should recognise the other: Position and Margin mean exactly what they mean there. What differs is that a picture has a size of its own, so it has three ways of being sized and a stamp has one.

type Position

type Position uint8

A Position says where on a page something goes.

const (
	Center Position = iota
	TopLeft
	TopCenter
	TopRight
	BottomLeft
	BottomCenter
	BottomRight
	MiddleLeft
	MiddleRight
)

The nine places a stamp can sit.

type Quad added in v0.26.0

type Quad struct {
	TopLeftX, TopLeftY         float64
	TopRightX, TopRightY       float64
	BottomLeftX, BottomLeftY   float64
	BottomRightX, BottomRightY float64
}

A Quad is one quadrilateral of a markup annotation, in the page's own coordinates: the four corners of the piece of text being marked.

⛔ THE ORDER IS THE ONE PRODUCERS AGREE ON, NOT THE ONE THE PROSE SAYS. Table 179 says the vertices are given "in counterclockwise order", and its own Figure 64 shows otherwise: (x1,y1) and (x2,y2) are the TOP edge, left then right, and (x3,y3), (x4,y4) the BOTTOM edge, left then right — which is a Z, not a loop. Every widely used producer and consumer follows the figure. A writer that follows the sentence produces highlights that render as bow-ties, or not at all, in most readers.

Spelling the corners out rather than taking eight numbers is the other half of that: an [8]float64 would let the mistake be made silently.

func QuadOf added in v0.26.0

func QuadOf(x0, y0, x1, y1 float64) Quad

QuadOf is the quadrilateral of an upright rectangle, which is what a line of horizontal text is.

type Quadding added in v0.29.0

type Quadding int

A Quadding is how a free text annotation's lines are justified: Table 174's /Q, where 0 is left, 1 centred and 2 right.

const (
	AlignLeft Quadding = iota
	AlignCentre
	AlignRight
)

type Redaction added in v0.28.0

type Redaction struct {
	// Page is which page, counting from one.
	Page int
	// Quads is where on it. A quadrilateral per piece, as a markup annotation
	// has: see [QuadOf] for the upright rectangle a line of text is.
	Quads []Quad
	// R, G and B are the colour painted over the region once the content is
	// gone, each from zero to one. The spec leaves the region transparent when
	// a redaction names no colour; this paints it, because an area that was
	// emptied and not marked is one a reader cannot tell from one that was
	// always blank.
	R, G, B float64
}

A Redaction names a region of a page whose content is to be REMOVED, and the colour to paint in its place.

⛔⛔ REMOVED, NOT COVERED, and that is the entire point. ISO 32000-1:2008 §12.5.6.23 on applying a redaction:

Conforming readers that support redaction annotations shall provide a
mechanism for applying content removal, and they shall remove all traces
of the specified content. If a portion of an image is contained in a
redaction region, that portion of the image data shall be destroyed;
clipping or image masks shall not be used to hide that data.

A black rectangle drawn over a paragraph is the standard data leak: the text is still in the content stream, so anyone's copy and paste — or `pdfops text` — reads it straight back out from under the box. The test that matters, and the one a drawn rectangle fails, is that the redacted string does not appear anywhere in the bytes that come out.

The region is in the page's own coordinates, up from the bottom left corner, in points — the same space Quad uses for a markup annotation.

type Shape added in v0.31.0

type Shape struct {
	// Page is 1-based.
	Page int
	// Kind is which shape; the zero value is a line.
	Kind ShapeKind
	// X0, Y0, X1, Y1 are the line's two ends, or the box a rectangle or an
	// ellipse is drawn inside, in the page's own points.
	X0, Y0, X1, Y1 float64
	// R, G, B are the colour of the line itself, in 0..1. The zero value is
	// black, which is what somebody drawing a line on a page means by it.
	R, G, B float64
	// Fill, when set, is the colour inside a rectangle or an ellipse and under
	// an arrowhead.
	//
	// ⛔ A POINTER, because Table 177's IC distinguishes "no colour;
	// transparent" — an array of NO elements — from a colour that happens to be
	// black. A value with a flag beside it would be two fields that can
	// disagree; a nil here is the spec's empty array.
	Fill *[3]float64
	// Width is how thick the line is, in points; zero means one.
	Width float64
	// Arrow draws an arrowhead at the X1, Y1 end of a line. It is Table 176's
	// ClosedArrow, which is "a triangular closed arrowhead filled with the
	// annotation's interior color, if any".
	Arrow bool
	// Author and Note are /T and /Contents. Both may be empty.
	Author, Note string
}

A Shape is one line, rectangle or ellipse over a page.

type ShapeKind added in v0.31.0

type ShapeKind uint8

A ShapeKind is which shape to draw.

const (
	// ShapeLine is a single straight line: "The purpose of a line annotation is
	// to display a single straight line on the page" (12.5.6.7).
	ShapeLine ShapeKind = iota
	// ShapeRectangle and ShapeEllipse are Table 177's Square and Circle, whose
	// names the spec itself apologises for: "Despite the names square and
	// circle, the width and height of the annotation rectangle need not be
	// equal." They are named here for what they draw.
	ShapeRectangle
	ShapeEllipse
)

type SignAppearance added in v0.40.0

type SignAppearance struct {
	// Rect is the box, x0 y0 x1 y1 in the page's own points (the page is
	// [SignOptions.Page]), no coordinate beyond 14400 in absolute value. When
	// signing an EXISTING empty signature field, the zero value means the field
	// widget's own /Rect, and only the field's FIRST widget gets the appearance
	// (a field shown in several places is drawn in one).
	Rect [4]float64
	// Image is an optional picture, in any format [Doc.Picture] reads. Its
	// aspect ratio is kept and it is fitted and centred in the box.
	Image []byte
	// Text is optional, drawn in Helvetica over the image; a \n starts a line
	// and long lines are wrapped. When Image and Text are both empty the text is
	// "Digitally signed by <the certificate's common name>" and a line with the
	// signing time in RFC 3339, UTC. Only characters WinAnsiEncoding has a code
	// for can be drawn: any other (Cyrillic, CJK, ...) is refused with
	// [ErrAppearanceText], in the default text too, when the common name has
	// one; pass a Text of your own then. A Unicode (Type0) font is future work.
	Text string
	// FontSize is the text's size in points: 0 means the largest, up to 24,
	// that fits the box; any other value is from 1 to 1000.
	FontSize float64
	// Color is the text's RGB, each 0..1; the zero value is black.
	Color [3]float64
	// MaxPixels is the largest Image, width times height, that will be
	// decoded; 0 means the default ceiling of [Doc.SetMaxPixels].
	MaxPixels int
}

SignAppearance is how a signature shows on its page. nil in SignOptions.Appearance keeps the signature invisible.

type SignOptions added in v0.39.0

type SignOptions struct {
	// Signer holds the private key (RSA, ECDSA or Ed25519, or any
	// crypto.Signer whose public key is one of those), and Certificate is its
	// certificate. Both are required. Chain is further certificates to embed.
	Signer      crypto.Signer
	Certificate *x509.Certificate
	Chain       []*x509.Certificate
	// Hash is the digest; SHA-256 when zero. SHA-1 is refused. PSS selects
	// RSASSA-PSS for an RSA key.
	Hash crypto.Hash
	PSS  bool

	// Field is the signature field's name. An existing, empty signature field
	// of that name is signed; when there is none, a new invisible field is
	// made on Page (counting from one; the first page when zero). An empty
	// Field picks the first of Signature1, Signature2… not already taken.
	Field string
	Page  int

	// Appearance makes the signature visible: a box on the page with an image
	// and/or text. nil keeps today's invisible signature, byte for byte.
	Appearance *SignAppearance

	// SubFilter is PKCS7Detached (the default) or CAdESDetached.
	SubFilter string

	// Name, Reason, Location and ContactInfo are the signer's claims, written
	// into the dictionary when not empty (Table 252). Time is /M, the claimed
	// time of signing; now when zero.
	Name, Reason, Location, ContactInfo string
	Time                                time.Time

	// Reserve is how many bytes of DER the /Contents placeholder holds. When
	// zero it is measured by signing once beforehand, which calls Signer
	// twice: a signer that asks a person for each signature (a smart card)
	// should be given a Reserve instead.
	Reserve int
}

SignOptions says who signs and what the signature dictionary says.

func (*SignOptions) LoadPKCS12 added in v0.41.0

func (o *SignOptions) LoadPKCS12(data []byte, password string) error

LoadPKCS12 reads a .p12 / .pfx file and sets o.Signer, o.Certificate and o.Chain from it; every other field of o is left alone. The password is the file's, as text; the empty password is tried before the absent one, as go-authn/pkcs12 does. LoadPKCS12 keeps neither data nor password after it returns, and o is untouched when it fails. A Go string cannot be erased, though: the password string the caller passed, and any copy made while decoding, stay in memory until the garbage collector reuses it. A caller that cares should hold the password in a []byte, convert it for this one call and zero the buffer afterwards (pdfops does). Do not zero data: the certificates it returns may point into it.

The certificate is not judged. Its validity dates, key usage and extended key usage are not checked, and neither is its chain to a root: this loads a key, a certificate and the certificates beside it, and the caller (before signing) and the verifier (afterwards) decide whether they are good enough.

type Stamp

type Stamp struct {
	Text     string
	Font     Font
	Size     float64    // in points; zero means twelve
	Colour   [3]float64 // red, green and blue, each from zero to one
	Opacity  float64    // zero means fully opaque
	Rotate   float64    // degrees, anticlockwise, about the text's own centre
	Position Position
	Margin   float64 // distance from the edge, in points; zero means 24
	Start    int     // the first value of {n}; zero means one
	Digits   int     // {n} padded to this many digits
}

A Stamp is a line of text drawn on a page.

The text may name what it is being drawn on: {page} is the page's number, {pages} the number of pages, and {n} a counter that starts wherever the stamp says and advances once per page stamped, which is what a numbering scheme like Bates needs.

type TextEdit added in v0.30.0

type TextEdit struct {
	// Page is 1-based.
	Page int
	// At is the operation to rewrite, as extract.Run.Op reports it.
	At extract.Span
	// Now is the text to draw instead. It may not be empty: a replacement by
	// nothing is a redaction, which Doc.Redact does properly — including
	// painting over the hole.
	Now string
}

A TextEdit replaces the whole text of one text-showing operation.

⛔ IT NAMES THE OPERATION, not the words. Finding a run by its text would be friendlier and wrong: the same words appear twice on many pages, and a verb that edited "the first one" would edit whichever the scan happened to reach first. extract.Run.Op is the span a caller already has from reading the page, and it says exactly which drawing is meant.

type Word added in v0.45.0

type Word struct {
	Text  string
	Box   [4]float64
	Angle float64
}

A Word is one recognised word to be made searchable.

Box is the word's rectangle in the page's own user space, y upwards: left, bottom, right, top. Text is in LOGICAL order, the order it is read in, whatever its script: a right-to-left word is given as it is typed, and the viewer's selection and search work on that order.

Angle is the baseline's angle in degrees anticlockwise, 0 for text that runs left to right along the page. A rotated word's Box is the rectangle BEFORE the turn: it is turned about its bottom left corner, so its width is the length of the word along the baseline and its height the height of its line.

type XFAReport added in v0.12.0

type XFAReport struct {
	// Sheets is how many pages the form came to.
	Sheets int
	// Drawn is how many elements were put on them.
	Drawn int
	// Hidden is how many the template asks not to be shown. They are placed —
	// they take up room, and what follows them sits below — and not drawn.
	Hidden int
	// Pictures is how many of the drawn elements carried one.
	Pictures int
	// Unplaced is everything the layout could not place, and every picture
	// that could not be drawn, one line each with the reason. Empty is the
	// ordinary case.
	Unplaced []string
}

An XFAReport says what laying a form out came to. A caller showing somebody the result needs to be able to say what is missing from it.

Directories

Path Synopsis
cmd
pdfops command
Command pdfops does to a PDF the things people actually want done to one: merge, extract, delete, reorder, rotate, crop, split, and read or strip the metadata.
Command pdfops does to a PDF the things people actually want done to one: merge, extract, delete, reorder, rotate, crop, split, and read or strip the metadata.
Package workflow runs a node graph of ops verbs, the way BentoPDF's PDF Workflow Builder does: input nodes, processing nodes and output nodes joined by typed sockets, executed in topological order.
Package workflow runs a node graph of ops verbs, the way BentoPDF's PDF Workflow Builder does: input nodes, processing nodes and output nodes joined by typed sockets, executed in topological order.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址