Text extraction from PDF documents, in content-stream order
README.md

pdf-text #

Text extraction from PDF documents in OCaml. Pdf_text.of_string reads a document, page_count counts its pages and page_text gives the text of a page in content-stream order, the order of poppler's pdftotext -raw.

let pages pdf =
  match Pdf_text.of_string pdf with
  | Error (`Msg e) -> Error e
  | Ok d ->
      Ok
        (List.init (Pdf_text.page_count d) (fun i ->
             match Pdf_text.page_text d (i + 1) with
             | Ok text -> text
             | Error (`Msg _) -> ""))

The text-showing operators and the text state follow ISO 32000-1 sections 9.3 and 9.4, and character codes map to Unicode as section 9.10 says:

  • a font's ToUnicode CMap first, ranges kept as ranges;
  • for a simple font, the glyph name its Encoding, Differences and base encoding give the code, mapped by the algorithm of the Adobe Glyph List Specification, so uni00E9, u1F600 and ligature names such as f_f_i decode; the built-in encoding of an embedded Type 1 program is read from its clear text;
  • for a composite font on a predefined UCS-2 or UTF-16 CMap, the code itself.

Ligatures expand to their letters. A space separates two glyphs when the gap between them is more than 0.4 times the width of the font's space glyph, and a line ends where the baseline moves by more than half the font size or the text moves back. A page whose content stream is malformed gives an error value; nothing raises.

Object, stream and content-stream parsing is camlpdf's. Fonts and ToUnicode CMaps are read by this library, which handles the cases camlpdf 2.9 drops: a simple font with Widths and no font descriptor, a Widths array of the wrong length, and a ToUnicode range whose destination crosses a byte boundary.

Reading order beyond content-stream order (columns, pdftotext -layout) is not done. A composite font is read with two-byte codes whatever its CMap.

The tests cite ISO 32000-1 sections 9.3, 9.4, 9.6, 9.7 and 9.10.3 (its Example 2 ToUnicode CMap verbatim), and the Adobe Glyph List Specification's examples. The interop test compares each page with pdftotext -raw on three PDFs built from the sources in test/interop/poppler/scripts by pdfTeX (Latin Modern in T1, Computer Modern in OT1) and Typst.

Installation #

opam install pdf-text

Licence #

ISC. It links camlpdf, which is LGPL-2.1 with the OCaml static-linking exception. The PDFs under test/interop/poppler/traces embed Latin Modern (GUST Font License), Computer Modern (SIL Open Font License) and Libertinus Serif (SIL Open Font License), which allow embedding.