Recursive AI

Searchable PDF (RecursiveAI.OneOcr.Pdf)

All oneocr docs

A page image keeps its look and gets an invisible text layer made from the page model, so that selection, search and copy in any PDF reader match the words on the page. SearchablePdf.FromImages/FromFiles/FromData and image.ToSearchablePdf(...) build a PDF from images; SearchablePdf.MakeSearchable adds layers to the pages of an existing PDF. PdfTextLayerWriter is the low-level piece both use: it draws one OcrPage into a OnePDF content builder. Everything runs locally; nothing here parses untrusted bytes except the content-stream rewrites described under "Replacing a third-party layer" and "Visible text that cannot be trusted".

The text layer

Words and their frame

The layer has one text object per word, in the page model's reading order (blocks, lines, words). A word is drawn in its frame: the rectangle, in the line's own axes, that spans the word along the line (the word's left and right edges) and the whole line across it (the line's top and bottom edges).

Why not the word's own box: word boxes are tight around ink, so a short word without ascenders or descenders ("of") is shorter than its neighbours ("by", "taken"). Drawn on their own boxes the words of one line would sit on different baselines, and a reader that groups text into lines would split the line or reorder its words (measured on OnePDF's extraction before the frame was introduced: words of one line came back in a different order). All words of a line therefore share the line's top and bottom.

Line axes: if the line carries a quad (turned, deskewed or tilted lines do), its corners P0 (top-left), P1 (top-right), P2 (bottom-right), P3 (bottom-left) are the line's frame; otherwise the frame is the line's axis-aligned bounds. A word that carries a quad on a line that does not uses its own quad as the frame.

Let u be the unit vector from P3 to P2, O = P3, and lo, hi the smallest and largest projection onto u of the four corners of the word's quad (or box), measured from O. With v = P0 − P3 (the way up, full line height, not necessarily perpendicular to u) the frame has the corners BL = O + lo·u, BR = O + hi·u, TL = BL + v, TR = BR + v. All of this happens in page units and is then mapped to PDF user space (below).

User space

OcrPage.ToPdf (x' = A x + C y + E, y' = B x + D y + F) maps page units to user space for a page that came from a PDF. For a page made from an image there is none, and the map is (s, 0, 0, −t, 0, H·t) with s = 72 / UnitsPerInch, t = 72 / VerticalUnitsPerInch and H = OcrPage.Height: one unit is 1/UnitsPerInch inch across and 1/VerticalUnitsPerInch inch down, the page is Width·s by Height·t points, y is flipped. The two are equal except for a capture with non-square pixels (a standard-mode fax, 200 by 100 dots per inch), whose page is then the right shape. UnitsPerInch is the image's declared resolution, the resolution given in OcrOptions.Dpi, or the estimate the page model carries (a diagnostic says it was estimated).

Text matrix

With BL', BR', TL' the mapped frame corners, w = |BR' − BL'|, h = |TL' − BL'|, b = (BR' − BL')/w, up = (TL' − BL')/h, n the number of glyphs (characters after the substitutions below) and the glyph cell 0.9 em above the baseline and 0.2 em below (1.1 em in all):

font size   fs = h / 1.1
scale       k  = w / (n · 0.5 · fs)                  every glyph is 0.5 em wide
text matrix [ b.x·k  b.y·k  up.x  up.y  e  f ]       (a b c d e f)
            (e, f) = BL' + up · (0.2 / 1.1) · h      the baseline sits 0.2 em above the frame's bottom edge

so the word's glyph cells exactly fill the frame: left edge and right edge on the word's, bottom and top on the line's, along the line's own axes. The horizontal scaling is in the matrix (a, b), not in a Tz operator.

Words with no text, with a degenerate or non-finite frame, and words the caller's filter rejects are skipped. Control characters (U+0000–U+001F, U+007F–U+009F) are dropped; a character the font has no glyph for (surrogates, anything beyond the Basic Multilingual Plane, the non-characters U+FFFE and U+FFFF) is written as U+FFFD. Right-to-left words keep the logical order of their text; positions are per word, so nothing is reordered.

Content stream

OnePDF's builder writes the layer as one new content stream:

q
  BT /OpF1 <fs> Tf 0 Tc 0 Tw 3 Tr  a b c d e f Tm  <glyph codes> Tj ET      one per word
  ...
Q

Render mode 3 paints nothing. For a PDF that already has content, OnePDF's overlay placement wraps the page's own streams in q/Q and appends the layer stream; the page's own streams are unchanged bytes. The layer stream is Flate-compressed.

The font

One embedded TrueType font, OneOcrText, generated by this library (GlyphlessFont): no outlines, and so no design and no licence to carry. Every glyph is empty and 0.5 em wide. It has a glyph for U+0020–U+007E, U+00A0–U+D7FF and U+E000–U+FFFD (63,421 glyphs plus .notdef), which covers charset-v1 (Latin, Greek, Cyrillic, common symbols) and all of the Basic Multilingual Plane that can be written. Tables: head, hhea, maxp, hmtx (one metric, the rest share its advance), loca (short, all empty), glyf, cmap (format 4, three ranges by idDelta), name, OS/2 (fsType 0, installable embedding), post (format 3). The bytes are fixed: no dates, no randomness.

OnePDF embeds the font as a Type 0 Identity-H font with a CIDFontType2 descendant and cuts it down when the file is saved to the glyphs used (a few hundred bytes to a few kilobytes), with /W widths and a /ToUnicode map built from the font's cmap, so text extraction recovers exactly the characters of the page model. All glyphs in one document share one font object. PDF/A requires embedded fonts, which is why a font is written even though nothing is painted.

Whole file cost, measured: a 58-word JPEG scan page grew by 3.4 KB (about 58 bytes per word, including the font subset and the page structure).

Tolerances (measured)

Checked with OnePDF's own extraction and the glyph quads it reports, on generated pages and on pages read by the recognizer:

CaseReader resultBound
Upright, and turned by 90, 180, 270°OnePDF words (text, order) and word boxestext and order exact; every edge of every word box within 0.003 pt of the frame
Skewed or tilted (2°, 5°, 8°, 10°, 37.5°, both signs)OnePDF glyph quads, in content ordertext exact; every glyph corner within 0.005 pt along and across the frame

The tests hold upright and quarter-turned pages to 0.05 pt and everything else to 0.1 pt.

Skewed text and OnePDF's own text layout. OnePDF's layout groups glyphs into lines and words with axis-aligned logic, so a line tilted by a few degrees comes back from ExtractText cut into pieces and out of order, even though every glyph is where it should be (the glyph quads are exact). The same happens to any PDF that carries slightly rotated text. Other readers (pdf.js, Acrobat, Preview, poppler) follow the text matrix. Pages of straight text (including pages turned by multiples of 90°, which is what orientation detection produces) extract whole. Handling slanted baselines is a OnePDF layout task, not a change in what is written here.

Images from images

FromImages reads each Image (every frame of a multi-frame image is a page) with the engine, creates a page of the size above, draws the image over it (q W 0 0 H 0 0 cm /OpIm1 Do Q, the image stretched to the page) and the layer after it. Embedding, in order of preference:

  1. JPEG file (FromFiles, FromData): one frame, no EXIF orientation other than 1, EmbedOriginalJpeg true, and OnePDF accepts the file: the file's bytes are the image stream (DCTDecode), unchanged. Tested byte for byte. A JPEG with an orientation tag is decoded (the pixels are turned upright, as the page model's coordinates are) and stored losslessly instead; so is an arithmetic-coded or lossless JPEG, which OnePDF refuses.
  2. PNG file, one frame, orientation 1: OnePDF's PNG pass-through (the IDAT data becomes a Flate stream with PNG predictors, byte for byte; palette, 1, 2, 4, 8 and 16 bits and tRNS are kept).
  3. Everything else, and decoded Image objects (TIFF, BMP, WebP, ..., a frame of a multi-frame image): the frame is read losslessly and stored as
    • 1-bit DeviceGray when every sample is 0 or 255 (fax and bilevel scans stay bilevel; also a color or gray file that happens to be pure black and white);
    • 8-bit DeviceGray when the frame is gray, or color with R = G = B everywhere;
    • 8-bit DeviceRGB otherwise (alpha is not applied; 16-bit and float samples are reduced to 8 bits, which is what the recognizer saw). The samples are written as a PNG whose rows pick one of the five PNG filters by the smallest sum of absolute values, deflated at the smallest-size setting, and handed to OnePDF's PNG pass-through. CCITT is read (by the image library) but not written: OnePDF's writer has no CCITT encoder, so a G3/G4 page is stored as Flate.

Measured: a 3-frame 1-bit letter-size TIFF (3,158,582 bytes uncompressed) became a 55,350-byte PDF; a 148,211-byte JPEG scan page became 151,575 bytes with its layer.

Rendering the PDF page at the image's own resolution reproduces its pixels (tested on a gray page and on 1-bit frames, with OneImage's PDF renderer).

Page boxes are not rounded: a 2550 × 3300 px image at 300 dpi is exactly 612 × 792 pt.

Making a PDF searchable

MakeSearchable(pdf, output, engine, options):

  1. Each page in SearchablePdfOptions.Pdf (default: all) is read like PdfOcr reads it, with the same trust rules (see pdf-bridge.md): text layers are kept, invisible third-party layers and garbled lines are not trusted, a text layer that disagrees with the rendered page is dropped, images without text are rendered at RenderDpi and recognized.
  2. A page gets a layer for the words whose Source is Ocr. A page with no such word (a page of born-digital text, a page whose images carry no text, a page whose invisible layer is trusted) is not touched; if no page needs a layer and no PDF/A is asked for, the output is the input, byte for byte. Pages outside FirstPage/PageCount are not read and not touched.
  3. The layer goes into a new content stream appended to the page (see "Content stream"). The page's own streams stay as they were, byte for byte, except as described next. Rendering is unchanged: the new stream paints nothing, and the tests compare rendered pages pixel for pixel.
  4. Everything outside the pages' content (fonts, forms, annotations, outlines, metadata, the /ID) is as it was; the file is written in full (not as an update).

Replacing a third-party layer

An earlier OCR step (a scanner, an OCR product, an earlier run of this library) leaves its text invisible, drawn in render mode 3 over the scan. That layer is replaced, not stacked, or readers would find every word twice. Without touching anything the page paints:

  • The page's content streams are decoded and joined (line feed between streams) and scanned once, by a small tokenizer (InvisibleTextRemover) that follows the PDF content-stream syntax: names, numbers, literal strings (nesting and escapes), hex strings, arrays, dictionaries, comments, inline images (BI … ID … EI, which are copied untouched and never read as operators).
  • The render mode is part of the graphics state, so it is tracked through Tr, q and Q (nesting up to 256).
  • The text-showing operators Tj, TJ, ' and " that execute while the mode is 3 are cut out. A cut ' becomes T* and a cut " becomes <aw> Tw <ac> Tc T*, so the line moves and the spacing parameters are kept.
  • Everything else, every byte outside a cut operator, is copied as it was, so what the page paints cannot change.
  • Cutting a show also drops its advance of the text matrix. That matters only when visible text is then shown on the same line without a positioning operator (Td, TD, Tm, T*, BT) in between. That case is detected and the page is left as it was (the page then carries both layers, and the result says so).
  • The rewritten content is stored as a new Flate stream that replaces /Contents; nothing else on the page changes.
  • Afterwards the page is read once with OnePDF's extraction; if invisible words remain (an invisible layer drawn from a form XObject, which is not entered, or any other construct the rewrite does not follow), SearchablePdfResult.Diagnostics says so.
  • The scan is bounded: one linear pass, no recursion, allocation proportional to the content, any ambiguity gives up without changing the page.

TrustExistingOcrLayer skips the replacement: the existing layer is the page's text layer, our layer is not added for the images it covers.

Visible text that cannot be trusted

A line whose characters are U+FFFD or private-use code points, or a text layer whose character map disagrees with what the page shows, is visible text: removing it would change what the page paints, so it stays. The recognized words are added as the invisible layer, and the visible runs are marked so that text extraction and copy return the recognized words and not the unreliable ones.

The mark is marked content with an empty replacement text (ISO 32000-1, 14.9.4, "Replacement text"):

/Span <</ActualText ()>> BDC  <the show operator with its operands>  EMC

Why empty: the recognized words are already on the page, each in its own frame. Giving the run the line's recognized text would write every word twice. An empty replacement says that the painted glyphs carry no text of their own.

Which shows are marked:

  • The page reader remembers the boxes of the visible text-layer lines it set aside (a garbled line; every line, when the layer failed the cross-check) and that it read from pixels.
  • A box is used only if the recognizer produced words inside it. A line with no replacement would otherwise vanish from extraction.
  • The page's content (decoded, streams joined) is scanned once by ActualTextMarker, which follows q/Q, cm, BT, Tm, Td, TD, TL, T*, Tr and the four showing operators with the same tokenizer as the earlier-layer remover. The start of a show is the origin of the text matrix mapped through the transformation matrix, tested against the boxes (each widened by a tenth of its smaller side). Advances of earlier shows are not tracked, since they need font widths: a show that continues a line takes the line's start, which is inside the line's box too.
  • Each such show (render mode other than 3) is wrapped on its own: the marker goes before its first operand and EMC after the operator. A sequence is one operator, so it nests with BT/ET, q/Q and marked content already on the page.
  • Everything else is copied byte for byte. Marked-content operators paint nothing and change no graphics state, so the page renders pixel for pixel as before (checked on the generated mixed file).
  • Afterwards the page is extracted once. If a word the reader took from the text layer (a trusted line) is missing, the rewrite is undone and the diagnostic says so.
  • The scan is bounded like the remover's: one pass, no recursion, graphics-state nesting up to 256, allocation proportional to the content (each wrapped show adds 33 bytes), and any ambiguity (an inline image that cannot be delimited) leaves the page as it was. Form XObjects are not entered.

Diagnostics has an entry per page with the number of runs marked; when the runs could not be marked (a show inside a form XObject, say), the entry says that the unreliable text stays next to the new layer.

What OnePDF's extraction returns for a marked page, measured on the generated file: the unreliable words are gone and the recognized ones come back, in the same words and order as the page model (Extract words equal the page model's words as a multiset, on a page with a garbled map on some lines and a wrong map on every line). The first word of each marked run still comes back flagged visible and with a box as wide as the run, because OnePDF stretches the replaced span's first glyph over the whole span and merges it with the invisible word that lies on it; the text is right, the box of that one word is not. A reader that ignores /ActualText shows both texts, as before.

PDF/A

SearchablePdfConformance.PdfA2b: images become a document written with OnePDF's PDF/A-2b save (XMP with pdfaid, output intent, embedded fonts, no forbidden features). MakeSearchable saves the edited document, then runs it through OnePDF's PDF/A converter; a file the converter refuses (for instance a font it cannot embed) throws OcrFormatException with OnePDF's list of reasons and writes nothing to a path output. The converter and the save are OnePDF's; OnePDF is not a validator and neither is this library.

Determinism

The same input bytes, the same options and the same engine give the same output bytes: at every degree of parallelism and on every kernel path (page models are bit-identical, see numerics.md), with no clock and no random values in the file. Numbers in content streams are rounded to four decimals by the builder. For a PDF made from images the file identifier is the first 16 bytes of the SHA-256 over, for each page, the image bytes that were embedded (the original file, or the PNG written for decoded pixels) and |<width>x<height>@<unitsPerInch>| (@<unitsPerInch>:<unitsPerInchY> when the two differ) and the page text; SearchablePdfOptions.DocumentId overrides it. A PDF given to MakeSearchable keeps its identifier.

Limits

  • Image pixel counts and page counts are checked by the engine (OcrLimits) before decoding; a PDF is limited by PdfOcrOptions.MaxFileBytes and OnePDF's own limits.
  • A frame is read in bands of 256 rows into one array of at most 2³¹ − 1 samples; more raises OcrLimitException.
  • Not done: vertical text and right-to-left layout of the layer beyond per-word positions; outlined text; form XObjects holding invisible layers or unreliable text; tagged PDF structure for the layer.