Khmer PDF to Word, tested
100%
of letters kept, 2 of 3 PDFs: the script
Whole words right, 3 typed PDFs
| Way | Chromium | LibreOffice | reportlab |
|---|---|---|---|
| LibreOffice Writer | 9.9% | 10.0% | 6.2% |
| pdf2docx | 76.4% | 89.1% | 16.2% |
| pdftotext | 92.9% | 92.9% | 14.7% |
| Tesseract: khm --psm 4 | 86.7% | 87.2% | 87.1% |
| The script: text, OCR if broken | 92.9% | 92.9% | 87.1% |
- On the good PDFs, pdftotext and the script kept every letter in order. Their misses are stray spaces.
pdftotext adds stray spaces inside words
Khmer puts no space between words, only between phrases. pdftotext guesses spaces from gaps, and some land inside words: គ្មា ន for គ្មាន.
- The text has 172 spaces. The script's .docx files have 244 and 256.
- Most stray spaces come right after the vowel ា.
- Ignore spaces, and the script kept 100% of words on those 2 PDFs.
- The script keeps them: in the text, stray and real spaces are the same character.
Why converters break Khmer
- Subscripts lost. LibreOffice Writer kept 0 of 342 subscript marks (coeng) from the Chromium and reportlab PDFs, and 239 from its own PDF.
- Text boxes. It also split each PDF into 975 to 1,383 text boxes.
- A weak copy. pdf2docx reads text with PyMuPDF, whose plain copy kept 630 and 722 of 828 words on the good PDFs.
- Private codes. The reportlab PDF's text holds 828 Private Use Area codes. pdf2docx skipped 2 of its pages with an XML error.
The script: text first, OCR if broken
The script keeps a good PDF's own text and sends a broken page to Tesseract khm.
python3 khmer_pdf_to_word.py in.pdf out.docx
- It needs Python 3, pandoc, Poppler and Tesseract with khm.
- Broken means under 20 Khmer letters, Private Use Area or NUL codes, or 3 or more marks out of place.
- It runs Tesseract with --psm 4. Homebrew's fast khm and khm best were within 0.7 points.
- It marks the .docx Khmer (km-KH) for complex script too, not pandoc's Arabic.
khmer_pdf_to_word.py, the whole script
"""Khmer PDF to Word: an editable .docx. The script of brasspage.com/khmer-pdf-to-word/
Needs on your PATH: Poppler (pdftotext, pdftoppm), Tesseract with the khm model, and pandoc. Python 3, stdlib only.
python3 khmer_pdf_to_word.py in.pdf out.docx [tessdata folder]
Each page: the PDF's own text (pdftotext). A page whose own text is broken is read by Tesseract (300 dpi, --psm 4)
instead. Broken: fewer than 20 Khmer letters (a scan, or an old font such as Limon that stores Latin codes),
Private Use Area characters, NUL characters, or 3 or more vowels or subscript marks out of place. Give a tessdata
folder that holds khm.traineddata if your Tesseract has no khm. Blank lines split paragraphs. pandoc writes the
.docx in Khmer (km-KH), and set_khmer() marks it Khmer for complex script too (km-KH, not pandoc's ar-SA). Each
page's choice goes to stderr.
"""
import html
import re
import subprocess
import sys
import unicodedata
import zipfile
KHMER = re.compile("[\u1780-\u17d3\u17dd]") # Khmer letters, vowels, signs and the coeng
# A vowel not after a letter, a coeng (subscript mark) not before a letter, a sign after no Khmer letter.
ORPHAN = re.compile(
"(?<![\u1780-\u17b3\u17c9\u17ca\u17cc])[\u17b6-\u17c5]|\u17d2(?![\u1780-\u17b3])|(?<![\u1780-\u17dd])[\u17c6-\u17d1\u17d3\u17dd]"
)
def broken(text):
"""Why a page's own text is broken, or None if it looks right."""
t = unicodedata.normalize("NFC", text).translate({0x200B: None, 0x200C: None, 0x200D: None})
if len(KHMER.findall(t)) < 20: # ponytail: an English-only page goes to OCR too
return "no Khmer text"
if re.search("[\ue000-\uf8ff]", t):
return "Private Use Area characters"
if "\x00" in t:
return "NUL characters"
if len(ORPHAN.findall(t)) >= 3: # one stray sign is a typing slip, not a broken page
return "vowels or subscript marks out of place"
return None
def ocr(pdf, n, tessdata):
page = ["pdftoppm", "-r", "300", "-gray", "-png", "-f", str(n), "-l", str(n), pdf]
png = subprocess.run(page, capture_output=True, check=True).stdout
cmd = ["tesseract", "-", "-", "-l", "khm", "--dpi", "300", "--psm", "4"]
if tessdata:
cmd += ["--tessdata-dir", tessdata]
r = subprocess.run(cmd, input=png, capture_output=True)
if r.returncode:
sys.exit(r.stderr.decode()) # Tesseract's own error, for example a missing khm model
return r.stdout.decode()
def paragraphs(text):
return [" ".join(b.split()) for b in re.split(r"\n\s*\n", text) if b.strip()]
def pdf_to_docx(pdf, docx, tessdata=None):
out = subprocess.run(["pdftotext", "-enc", "UTF-8", pdf, "-"], capture_output=True, check=True).stdout.decode()
paras = []
for n, text in enumerate(out.split("\f")[:-1], 1): # pdftotext ends every page with a form feed
why = broken(text)
print(f"page {n}: " + (f"OCR ({why})" if why else "text layer"), file=sys.stderr)
paras += paragraphs(ocr(pdf, n, tessdata) if why else text) # ponytail: a paragraph across a page break stays two
body = "".join(f"<p>{html.escape(p)}</p>\n" for p in paras)
subprocess.run(["pandoc", "-f", "html", "-o", docx, "-M", "lang=km-KH"], input=body.encode(), check=True)
set_khmer(docx)
def set_khmer(docx):
"""pandoc's styles keep Arabic as the complex-script language (w:bidi="ar-SA"). Make it Khmer."""
with zipfile.ZipFile(docx) as z:
parts = [(info, z.read(info)) for info in z.infolist()]
with zipfile.ZipFile(docx, "w") as z:
for info, data in parts:
if info.filename == "word/styles.xml":
data = data.replace(b'w:bidi="ar-SA"', b'w:bidi="km-KH"')
z.writestr(info, data)
if __name__ == "__main__":
if len(sys.argv) < 3:
sys.exit("usage: python3 khmer_pdf_to_word.py in.pdf out.docx [tessdata folder]")
pdf_to_docx(*sys.argv[1:4])
Limon to Unicode, offline
Old Limon fonts draw Khmer on Latin codes. I had no Limon file, so 2 free tools wrote codes for our 828 words, and 2 read them back.
| Codes by | seanghay | chamnap |
|---|---|---|
| seanghay | 801 | 780 |
| kfc | 783 | 778 |
Convert Limon text with seanghay's tool
npm install khmer-unicode-converter@1.0.1
pdftotext -enc UTF-8 limon.pdf limon.txt
node --input-type=module -e "import fs from 'node:fs'; import { convertLegacyToUnicode } from 'khmer-unicode-converter'; fs.writeFileSync('khmer.txt', convertLegacyToUnicode(fs.readFileSync('limon.txt', 'utf8'), 'limon'))"
pandoc -f markdown khmer.txt -o khmer.docx -M lang=km
- Name the font. The package's default is abc-zwsp, another old Khmer font.
- On my look-alike PDF, the .docx held 783 of 828 words. pdftotext added stray spaces to half the pages.
Where Limon loses letters
- One code, two letters. Limon has one code for the subscripts ្ដ and ្ត, which look the same.
- Our text has 23 of them. seanghay read all back as ្ត, chamnap as ្ដ.
- Look-alikes. ឲ came back as ឱ, and ៖ as ៈ.
- No code. The old letters ឝ and ឞ have no Limon code, so 7 were lost.
A look-alike Limon PDF
My look-alike PDFs drew each tool's codes in DejaVu Sans. The Limon fonts name no license that I found.
pdftotext copied 0 Khmer words, and the script sent every page to OCR. Mine draw Latin letters, so OCR of real Limon is untested.
Our Actor reads Khmer
Our Apify Actor, PDF to Markdown OCR, reads Khmer. I did not run it on these PDFs.
- With Khmer set, a page whose own text is mostly Khmer goes to OCR, at $0.006 a page, plus a $0.00005 start fee a run.
- It reads Khmer with --psm 4, like the script.
- Runs bill to your Apify account. Your files go to Apify's servers.
What I tested, and what I did not
- No Microsoft Word, no online converter, no real Limon file.
- Typed PDFs only. For scans, see Khmer OCR.
How I tested
- Text: 12 passages from 12 random Khmer Wikipedia articles (CC BY-SA 4.0), one a page. I quote no passage, only single words.
- They hold 828 words, 342 subscript marks and 172 spaces.
- PDFs in Noto Sans Khmer 2.004: Chromium 153 print to PDF and LibreOffice 26.8.1.1 export, both with lang km, and reportlab 5.1.2 with shaping on.
- Ways: LibreOffice Writer (soffice --infilter=writer_pdf_import), pdf2docx 0.5.13 with PyMuPDF 2.2, pdftotext from Poppler 26.03.0, Tesseract 5.5.4 at 300 dpi with tessdata_fast khm and tessdata_best khm 4.1.0, pandoc 3.13.
- Words: Khmer puts no space between words, so I split text into words with the ICU word list that Chrome uses. Words right: truth words found whole in the .docx text, each counted as often as it appears.
- Letters: Khmer letters and signs, found in order. I scored the text inside each .docx. LibreOffice on this Mac used no Khmer font when it printed the 4 .docx files made from the Chromium PDF, so I did not check how they look.
- Limon writers: seanghay's khmer-unicode-converter 1.0.1 from npm and kfc 0.2.3 from PyPI. Readers: seanghay's and chamnap's. All ran offline, from pinned versions.
- KhmerConverter, the tool seanghay's package ports, needs Python 2, which this Mac does not have.
- The look-alike PDFs: each writer's codes drawn by reportlab in DejaVu Sans, so they copy back the codes, but do not look like a Limon PDF.
Sources
- pdf2docx is MIT. It needs PyMuPDF, which is AGPL-3.0 or a paid license.
- khmer-unicode-converter (seanghay): GPL-2.0 or later in its package.json. Its LICENSE file holds the LGPL 2.1 text.
- kfc on PyPI: GPL-3.0 or later. It writes Limon only.
- chamnap's khmer_unicode_converter: ISC in its package.json, with no license file.
- KhmerConverter, by the Khmer Software Initiative, holds the Limon table that seanghay's package uses.
- tessdata_best and tessdata_fast for Tesseract (Apache-2.0).
- Font: Noto Sans Khmer, OFL.
- Scripts and results stay in our private repo, in research/bench/khmer-pdf-to-word-2026-11-28/.
- We make the Apify Actor, not these tools.
Questions people ask
How do I convert a Khmer PDF to Word for free?
Keep the PDF's own text where it is right, and OCR the other pages with Tesseract khm and --psm 4. The free script on this page does both, then pandoc writes the .docx. It kept every letter of 2 typed PDFs, plus some stray spaces.
How do I convert Limon text to Unicode?
Use seanghay's khmer-unicode-converter, and name the font limon. It read back 801 of 828 words from its own Limon codes, offline. I had no real Limon file, only codes that 2 tools wrote.
Why does text from a Limon PDF come out as Latin letters?
Limon fonts draw Khmer letters on Latin codes, so a copy gives you the codes: Exµr for ខ្មែរ. Convert the codes, or OCR the page.