Japanese PDF to Word, tested
100%
characters in order, vertical too: the script
Characters in order, 4 of the 6 PDFs
| Way | Chromium, across | Chromium, vertical | LibreOffice, vertical | No font map, vertical |
|---|---|---|---|---|
| LibreOffice Writer | 100.0% | 7.3% | 5.6% | 0.0% |
| pdf2docx | 100.0% | 6.2% | 35.7% | 3.0% |
| pdftotext | 100.0% | 19.1% | 7.7% | 2.9% |
| Our Actor | 100.0% | 6.7% | 4.4% | 1.7% |
| The script: text, OCR if broken | 100.0% | 100.0% | 100.0% | 91.1% |
- No font map: the Chromium vertical PDF with its ToUnicode maps deleted, so its text copies out as other letters.
- On the Chromium and LibreOffice across PDFs, every way but the script kept all 270 furigana characters.
Why converters break Japanese
- Rows, not columns. Plain pdftotext read vertical pages across the columns. pdftotext -raw kept the order, but put 2,557 spaces between characters on the Chromium vertical PDF.
- Furigana in the text. From the LibreOffice PDFs, pdftotext -raw and PyMuPDF put all 97 readings next to their kanji, as in ふきん附近.
- Look-alike radicals. Chromium's PDF maps 49 kanji, such as 人, to Kangxi radicals like ⼈. LibreOffice Writer and our Actor kept all 235 uses as radicals. ⼈ is a different character code from 人, so an exact search for 人 does not find it.
- Slow on columns. pdf2docx took about 4 minutes on each Chromium vertical PDF.
The script: text first, OCR if broken
It copies each page in the PDF's own order, drops the furigana, and OCRs a broken page with Tesseract.
python3 japanese_pdf_to_word.py in.pdf out.docx
- It needs Python 3, pandoc, Poppler and Tesseract with jpn and jpn_vert.
- It drops words under 0.7 of the page's usual text size. Furigana is about half size. None was left on the 4 PDFs with font maps.
- It puts no space between Japanese characters. With spaces ignored, all 80 sentences came out whole on the 4 PDFs with font maps.
- Broken: under 20 Japanese characters, under half Japanese, or Private Use Area, U+FFFD or NUL codes.
- pandoc marks the .docx text Japanese (ja-JP).
japanese_pdf_to_word.py, the whole script
"""Japanese PDF to Word: an editable .docx. The script of brasspage.com/japanese-pdf-to-word/
Needs on your PATH: Poppler (pdftotext, pdftoppm), Tesseract with the jpn and jpn_vert models, and pandoc.
Python 3, stdlib only.
python3 japanese_pdf_to_word.py in.pdf out.docx [tessdata folder]
Each page: the PDF's own words in the order the PDF stores them (pdftotext -raw -bbox), so vertical columns stay in
order. Furigana (ruby) is printed at about half size, so words under 0.7 of the page's usual text size are dropped.
A page whose words are taller than wide in sum is vertical. Words join with no space between two Japanese
characters. A line that ends short of the page's longest line by 2 text sizes or more ends its paragraph.
A page whose own text is broken is read by Tesseract (300 dpi) with jpn and with jpn_vert, and the reading with the
higher mean confidence wins. Broken: fewer than 20 Japanese characters, or under half of the page's characters
Japanese (a font with no Unicode map copies out as other letters), or Private Use Area, U+FFFD or NUL characters.
pandoc writes the .docx in Japanese (w:eastAsia="ja-JP"). Each page's choice goes to stderr.
"""
import html
import re
import statistics
import subprocess
import sys
import tempfile
from pathlib import Path
# Kanji, kana and Japanese punctuation and full-width forms
JA = "\u3000-\u303f\u3040-\u30ff\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef"
JAPANESE = re.compile(f"[{JA}]")
GAP = re.compile(f"(?<=[{JA}])\\s+(?=[{JA}])") # whitespace between two Japanese characters
WORD = re.compile(r'<page |<word xMin="([-\d.]+)" yMin="([-\d.]+)" xMax="([-\d.]+)" yMax="([-\d.]+)">(.*?)</word>')
def join(parts):
"""Words or lines joined by one space, then no space between two Japanese characters."""
return GAP.sub("", " ".join(parts))
def pages_words(pdf):
"""Per page: (x0, y0, x1, y1, text) of each word, in the order the PDF stores them."""
out = subprocess.run(["pdftotext", "-raw", "-bbox", "-enc", "UTF-8", pdf, "-"], capture_output=True, check=True)
pages = []
for m in WORD.finditer(out.stdout.decode()):
if m[0] == "<page ":
pages.append([])
else:
pages[-1].append((*map(float, m.groups()[:4]), html.unescape(m[5])))
return pages
def paragraphs(words):
"""The page's paragraphs, furigana dropped."""
if not words:
return []
# ponytail: one direction a page. Poppler gives a horizontal row as wide words, a vertical column as one tall word
# a character, so the sums tell them apart. A page of single characters set horizontally would read as vertical.
vertical = sum(w[3] - w[1] for w in words) > sum(w[2] - w[0] for w in words)
size = [(w[2] - w[0]) if vertical else (w[3] - w[1]) for w in words] # across the line: the text size
usual = statistics.median([s for s, w in zip(size, words) for _ in w[4]]) # a median over characters
kept = [w for s, w in zip(size, words) if s >= 0.7 * usual]
a0, a1 = (1, 3) if vertical else (0, 2) # along the line: y down a column, x along a row
lines = [[kept[0]]]
for a, b in zip(kept, kept[1:]):
if b[a0] < (a[a0] if vertical else a[a1]) - usual: # back up to the next column, or left to the next row
lines.append([])
lines[-1].append(b)
end = max(ln[-1][a1] for ln in lines)
paras = [[]]
for ln in lines:
paras[-1].append(join(w[4] for w in ln))
if ln[-1][a1] < end - 2 * usual:
paras.append([])
return [join(p) for p in paras if p]
def broken(text):
"""Why a page's own text is broken, or None if it looks right."""
chars = re.sub(r"\s", "", text)
ja = len(JAPANESE.findall(chars))
if ja < 20: # ponytail: an English-only page goes to OCR too
return "no Japanese text"
if ja < len(chars) / 2:
return "most characters are not Japanese"
if re.search("[\ue000-\uf8ff\ufffd\x00]", chars):
return "Private Use Area, U+FFFD or NUL characters"
return None
def ocr(pdf, n, tessdata):
"""Tesseract with jpn and jpn_vert; the reading with the higher mean word confidence, and its model."""
png = subprocess.run(["pdftoppm", "-r", "300", "-gray", "-png", "-f", str(n), "-l", str(n), pdf], capture_output=True, check=True).stdout # fmt: skip
best = None
with tempfile.TemporaryDirectory() as tmp:
for lang in ("jpn", "jpn_vert"):
cmd = ["tesseract", "-", f"{tmp}/{lang}", "-l", lang, "--dpi", "300"]
cmd += ["--tessdata-dir", tessdata] if tessdata else []
out = ["-c", "tessedit_create_txt=1", "-c", "tessedit_create_tsv=1"] # no config files needed
r = subprocess.run(cmd + out, input=png, capture_output=True)
if r.returncode:
sys.exit(r.stderr.decode()) # Tesseract's own error, for example a missing model
rows = [ln.split("\t") for ln in Path(f"{tmp}/{lang}.tsv").read_text().splitlines()[1:]]
conf = [float(x[10]) for x in rows if len(x) == 12 and x[0] == "5" and x[11].strip()]
mean = sum(conf) / len(conf) if conf else 0
if best is None or mean > best[0]:
best = (mean, lang, Path(f"{tmp}/{lang}.txt").read_text())
paras = [join(b.split()) for b in re.split(r"\n\s*\n", best[2]) if b.strip()]
return paras, f"{best[1]}, mean confidence {best[0]:.0f}"
def pdf_to_docx(pdf, docx, tessdata=None):
paras = []
for n, words in enumerate(pages_words(pdf), 1):
page = paragraphs(words)
why = broken("".join(page))
if why:
page, model = ocr(pdf, n, tessdata)
why += f"; {model}"
print(f"page {n}: " + (f"OCR ({why})" if why else "text layer"), file=sys.stderr)
paras += page # 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=ja-JP"], input=body.encode(), check=True)
if __name__ == "__main__":
if len(sys.argv) < 3:
sys.exit("usage: python3 japanese_pdf_to_word.py in.pdf out.docx [tessdata folder]")
pdf_to_docx(*sys.argv[1:4])
Broken pages: jpn or jpn_vert
- Tesseract jpn read 92.1% of characters across and 1.7% in columns.
- jpn_vert read 90.5% in columns and 2.1% across.
- The script runs both and keeps the higher mean confidence. It picked right on all 24 broken pages.
Scanned pages read worse
On 35 vertical book scans in our Tesseract Japanese test, the same fast jpn_vert got 79.0% of the characters right.
NDLOCR-Lite found 98.8% of the characters on the same 35 scans.
Our Actor: across yes, columns not yet
Our Apify Actor, PDF to Markdown OCR, turns PDFs into Markdown in one call, Japanese too.
- It kept 100% on the across PDFs with font maps, but 4.4% and 6.7% on the vertical ones.
- For Japanese its OCR has jpn only, no jpn_vert: 1.7% on the vertical PDF with no font map.
- 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 Adobe Acrobat, no online converter.
- Typed PDFs only, one paragraph a page. No tables, headings or pages with 2 or more blocks of columns.
How I tested
- Text: 12 passages from proofread ja.wikisource pages, the first test page of each of the 12 books in our Tesseract Japanese test. I quote only single words.
- They hold 2,685 kanji and kana, 80 sentences and 97 furigana readings.
- PDFs in Noto Sans JP 2.004: Chromium 153 (Playwright) print to PDF and LibreOffice 26.8.1.1 export, each across and vertical.
- The no font map PDFs are the Chromium ones with every ToUnicode map deleted.
- 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 jpn and jpn_vert 4.1.0, pandoc 3.13.
- Our Actor: its own page code from our repo, run on this Mac with language jpn, then pandoc.
- Characters in order: the kanji and kana of the passages found in order in each .docx text, after NFKC. NFKC counts a radical as its kanji.
- Sentences: cut after 。, ! and ?, and found whole, character for character.
Sources
- pdf2docx is MIT. It needs PyMuPDF, which is AGPL-3.0 or a paid license.
- tessdata_fast for Tesseract (Apache-2.0).
- Font: Noto Sans JP, OFL.
- Scripts and results stay in our private repo, in research/bench/japanese-pdf-to-word-2026-11-28/.
- We make the Apify Actor, not these tools.
Questions people ask
How do I convert a Japanese PDF to Word for free?
Copy the PDF's own text in the order the PDF stores it, drop the furigana, and OCR the broken pages. The free script on this page does that: 100% of characters in order on 4 typed PDFs with font maps, 91.1% on a vertical PDF with no font map.
Why is the text from my vertical Japanese PDF out of order?
Plain pdftotext reads vertical pages across the columns. It kept 19.1% and 7.7% of characters in order on the Chromium and LibreOffice vertical PDFs. On those 2 PDFs, pdftotext -raw kept 100% in order, but put spaces between characters.
Why does my copied Japanese text have extra kana in it?
That is the furigana printed above or beside the kanji. On the Chromium and LibreOffice across PDFs, LibreOffice Writer, pdf2docx, pdftotext and our Actor kept all 270 furigana characters. The script drops words under 0.7 of the usual text size. None were left on the 4 PDFs with font maps.