The pipeline

From bytes to Khmer text in seven steps.

  1. Load the filekhpdf parses the PDF with lopdf. PDFs saved several times keep old copies of some objects; khpdf always uses the copy the file's index points to, so the output is the same on every run.
  2. Understand each fontFor every font on the page, khpdf collects all the evidence about which glyph is which letter: the PDF's /ToUnicode map, the embedded font's cmap and glyph names, its GSUB substitution rules run backwards, and for Khmer OS fonts the family's fixed glyph layout. For Khmer, the embedded font wins over /ToUnicode, which Word fills with wrong labels. See Problems.
  3. Interpret the pagekhpdf runs the page's drawing instructions, tracking position, size and font for every glyph, including text inside nested drawing groups.
  4. Join fragments in drawing orderKhmer marks are often drawn as separate tiny fragments, shifted down or placed over the previous letter. khpdf joins fragments in the order they are drawn, which keeps each mark with its syllable. A row drawn as one stretched string is split at its wide gaps, so table cells stay apart.
  5. Clean up the pageSideways pages are turned so the text reads left to right; text drawn twice for an outline or shadow effect is dropped.
  6. Fix the KhmerLimon text is decoded from its Latin letters. Pre-base vowels and แŸ’แžš, which PDFs store before the consonant, are moved after it; split vowels are joined; every syllable is put in canonical Unicode order.
  7. Rebuild the layoutFragments are grouped into lines, lines into headings, paragraphs, lists and tables. Table columns are matched by overlap, so centred headers line up with their data. The result is rendered as Markdown, text or JSON.

Every step exists because of a real document. Problems khpdf fixes shows them one by one.