Run a scanned book through the obvious command and you get the text and nothing else:
tesseract page-001.png out -l oriOne wall of lines. No headings, no paragraphs, no page boundaries — and if the book is in Odia, Word may show you a column of empty rectangles even when the text is fine, because the file never told it which font to use for a complex script.
Both problems have the same shape: the information exists, and the easy path throws it away. Tesseract knows where every line sat on the page and how tall its glyphs were. WordprocessingML has a property for the font Word uses on complex scripts. You just have to ask for the first and emit the second.
Requirements
- Go 1.21 or newer. No modules — the standard library covers zip and XML.
- poppler-utils.
pdftotextandpdftoppm. On Debian,apt install poppler-utils. - Tesseract 5 and your traineddata.
apt install tesseract-ocr tesseract-ocr-orifor Odia; other languages follow the same naming. - A font with the glyphs, on whatever machine opens the .docx. Nirmala UI ships with Windows; Noto Sans Oriya is the free alternative.
Take the text layer when there is one
Not every PDF is a scan. If the file already carries text, OCR is slower and strictly worse, so try the cheap path first and treat a nearly empty result as proof that the pages are images.
if bin, err := tool("pdftotext"); err == nil {
out := filepath.Join(dir, "all.txt")
if run(bin, "-enc", "UTF-8", pdf, out) == nil {
if b, _ := os.ReadFile(out); len(bytes.TrimSpace(b)) > 20 {
return textParas(string(b)), "text layer", nil
}
}
}Twenty bytes is a deliberately low bar. Scanned PDFs often carry a stray label or a page number in a real text layer, and anything under that threshold is not a document.
For this path a blank line ends a paragraph, wrapped lines rejoin so Word can reflow them, and pdftotext’s form feed marks a page boundary — remember that character, it comes back to bite later.
Render pages at 300 dpi
pdftoppm writes one PNG per page. Tesseract’s own guidance is that it works
best at 300 dpi or above, and below roughly 200 accuracy falls off a cliff.
if err := run(ppm, "-r", "300", "-png", pdf, filepath.Join(dir, "page")); err != nil {
return nil, "", err
}
pngs, err := filepath.Glob(filepath.Join(dir, "page-*.png"))
sort.Strings(pngs)pdftoppm zero-pads every page number to the width of the last one, so
page-001.png … page-300.png sort lexically into page order. No numeric
parsing needed.
Ask for hOCR, not text
This is the whole trick. Add hocr as the config argument and Tesseract emits
XHTML with a bounding box on every block, paragraph, line and word.
run(tess, png, base+"-auto", "-l", *lang, "--psm", "1", "hocr")--psm 1 is full automatic page segmentation with orientation detection: it is
what produces ocr_par blocks and a sensible reading order. The output looks
like this:
<div class='ocr_carea' title="bbox 100 100 1000 320">
<p class='ocr_par' title="bbox 100 100 1000 320">
<span class='ocr_line' title="bbox 200 100 1000 200; x_size 100">
<span class='ocrx_word' title='bbox 200 100 500 200; x_wconf 96'>ଓଡ଼ିଆ</span>
<span class='ocrx_word' title='bbox 520 100 1000 200; x_wconf 96'>ଭାଷା</span>
</span>
</p>
</div>Three things in there are worth the whole exercise. ocr_par tells you where
paragraphs begin and end. bbox tells you where each line sat, which is
alignment and indentation. And x_size is Tesseract’s estimate of the glyph
height on that line, which is the closest thing to a font size you will get.
Parse hOCR as a token stream
Everything you need lives in a class attribute and a title string, not in
the nesting — so unmarshalling into structs is more work than walking tokens.
Set the decoder to non-strict HTML mode, because hOCR is XHTML with an external
DTD and HTML entities.
func parseHOCR(b []byte) (pars [][]pline, photos []box) {
d := xml.NewDecoder(bytes.NewReader(b))
// hOCR is XHTML: unpaired tags, HTML entities and a DTD the decoder
// must not try to fetch.
d.Strict = false
d.AutoClose = xml.HTMLAutoClose
d.Entity = xml.HTMLEntity
var cur []pline
inWord := false
flush := func() {
if len(cur) > 0 {
pars, cur = append(pars, cur), nil
}
}
for {
tok, err := d.Token()
if err != nil {
break
}
switch t := tok.(type) {
case xml.StartElement:
class, title := attr(t, "class"), attr(t, "title")
v := titleVals(title)
switch {
case class == "ocr_photo":
photos = append(photos, boxOf(v))
case class == "ocr_par":
flush()
case lineClass[class]:
cur = append(cur, pline{bbox: boxOf(v), xsize: first(v["x_size"])})
case class == "ocrx_word":
inWord = len(cur) > 0
}
case xml.CharData:
if inWord {
cur[len(cur)-1].text += strings.TrimSpace(string(t))
}
case xml.EndElement:
if inWord && t.Name.Local == "span" {
inWord = false
cur[len(cur)-1].text += " "
}
}
}
flush()
return pars, photos
}Two details that are easy to get wrong:
A line is not always ocr_line. Tesseract labels lines by what it thinks
they are for. Accept the lot, or captions and running headers vanish:
var lineClass = map[string]bool{
"ocr_line": true, "ocr_caption": true, "ocr_textfloat": true,
"ocr_header": true, "ocr_footer": true,
}The title attribute is a mini format, bbox 1 2 3 4; x_size 12.5, and it
also carries non-numeric properties such as image "page-001.png". Split on
;, take the first field as the key, parse the rest as floats and drop any
property whose values do not all parse.
Turn boxes into formatting
Now the actual inference. The rule that makes this robust is that everything
is relative to the page, never to absolute pixels — otherwise the output
changes the moment you change -r.
func layout(pars [][]pline, basePt int) []para {
// The median line height on the page is body text; everything scales off it.
body := median(sizes)
col := /* union of every line bbox: the text column */
var out []para
for _, p := range pars {
b := /* union bbox of this paragraph */
ratio := median(lineSizes) / body
left, right := b.x0-col.x0, col.x1-b.x1
out = append(out, para{
text: clean(text.String()),
sz: 2 * clamp(int(math.Round(ratio*float64(basePt))), 6, 48),
bold: ratio >= 1.25,
// Centred means pulled in from both margins by about the same amount.
center: left > col.w()/20 && abs(left-right) < col.w()/16,
indent: p[0].bbox.x0-b.x0 > col.w()/40,
top: b.y0,
})
}
sort.SliceStable(out, func(i, j int) bool { return out[i].top < out[j].top })
return out
}Read that as four heuristics:
- Font size is the paragraph’s median glyph height divided by the page’s
median glyph height, times your base point size. Body text lands on 12 pt
because it is the median.
w:szis in half-points, hence the2 *. - Bold is a line 25% taller than body text. Crude, and the only weight signal available — see the FAQ.
- Centred is a paragraph pulled in from both margins by roughly equal amounts. Comparing against the text column rather than the paper edge is what makes it survive a crooked scan.
- Indented is a first line that starts further right than the rest of its own paragraph.
Sorting by the top of the bounding box restores reading order after the sparse pass below appends out-of-order lines.
Recover headings hidden in picture regions
Chapter titles in a real book are often set inside a coloured band or a
decorative box. Page segmentation classifies that whole region as ocr_photo
and never reads it, so the heading is simply missing from the output.
The fix is a second pass in sparse mode, --psm 11, which finds text anywhere
without caring about layout — and then keeping only the lines that land
inside a region the first pass called a picture:
if b, err := ocr("-sparse", "11"); err == nil {
sparse, _ := parseHOCR(b)
for _, p := range sparse {
for _, l := range p {
// Only lines the layout pass refused to read; sparse mode has no
// paragraph structure worth keeping for the rest of the page.
if letters(l.text) >= 3 && insideAny(l.bbox, photos) {
pars = append(pars, []pline{l})
}
}
}
}It doubles OCR time, so make it a flag. It is worth it on books with designed chapter openers and pointless on a plain typescript.
Write the .docx yourself
A .docx is a zip with three parts in it. There is no reason to add a dependency for that.
- converted.docx (zip)
- [Content_Types].xml
- _rels/
- .rels
- word/
- document.xml
[Content_Types].xml declares the MIME type of each part, _rels/.rels points
at the main document, and word/document.xml is the content. archive/zip
writes all three:
var buf bytes.Buffer
z := zip.NewWriter(&buf)
for _, p := range parts {
w, _ := z.Create(p[0])
io.WriteString(w, p[1])
}
if err := z.Close(); err != nil {
return nil, err // Close writes the central directory — before Bytes(), always
}
return buf.Bytes(), nilThe complex-script properties are not optional
This is the part that makes Odia — or Hindi, Tamil, Arabic, Thai — actually
render. Word applies w:rFonts w:ascii and w:sz to Latin characters, and
consults an entirely separate set of properties for complex scripts. Per the
ECMA-376 definition, w:szCs “specifies the font size which shall be applied
to all complex script characters in the contents of this run”. Set only the
plain twin and Word falls back to whatever font it likes, which is how you get
a page of empty boxes.
So every run carries both halves:
<w:rPr>
<w:rFonts w:ascii="Nirmala UI" w:hAnsi="Nirmala UI" w:cs="Nirmala UI"/>
<w:b/><w:bCs/>
<w:sz w:val="24"/><w:szCs w:val="24"/>
<w:lang w:bidi="or-IN"/>
</w:rPr>w:cs names the complex-script font, w:bCs and w:szCs are the weight and
size that reach Indic glyphs, and w:lang w:bidi tags the run’s complex-script
language so spell-check and font fallback pick the right one.
Page breaks, and the form feed that breaks the file
Keep the PDF’s pagination by making the first paragraph of each page carry a break:
if p.brk {
body.WriteString(`<w:r><w:br w:type="page"/></w:r>`)
}And then strip control characters from every string you write, because XML 1.0 forbids them and Word rejects the whole document over one:
// pdftotext's page-break form feed (0x0C) is the usual culprit.
func clean(s string) string {
return strings.TrimSpace(strings.Map(func(r rune) rune {
switch {
case r == '\t':
return ' '
case r < 0x20, r == 0x7f, r == 0xfffe, r == 0xffff:
return -1
}
return r
}, s))
}Escaping does not save you here:  is just as illegal as the raw byte.
The character has to go. Use xml.EscapeText for the rest — a book with an
ampersand in it will otherwise produce a file Word refuses to open, and the
error message will not mention the ampersand.
Serve it
The HTTP layer is short and the interesting parts are the guards:
func convert(w http.ResponseWriter, r *http.Request) {
// Cap the body before parsing, not after.
r.Body = http.MaxBytesReader(w, r.Body, *maxSize)
if err := r.ParseMultipartForm(32 << 20); err != nil {
http.Error(w, "upload too large or malformed", http.StatusBadRequest)
return
}
defer r.MultipartForm.RemoveAll()
dir, _ := os.MkdirTemp("", "pdf2word")
defer os.RemoveAll(dir) // rendered pages and hOCR both live here
// Cheap sniff: poppler should never see a file that is not a PDF.
if head, _ := os.ReadFile(pdf); !bytes.HasPrefix(head, []byte("%PDF-")) {
http.Error(w, "not a PDF", http.StatusBadRequest)
return
}
...
}Return the result as an attachment, and use the filename* form so a
non-ASCII source name survives:
w.Header().Set("Content-Type",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document")
w.Header().Set("Content-Disposition",
`attachment; filename="converted.docx"; filename*=UTF-8''`+url.PathEscape(name))Package it
The Go side builds to one static binary, so the runtime image only needs the two tools:
FROM golang:1.21-alpine AS build
WORKDIR /src
COPY go.mod main.go index.html ./
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /pdf2word .
# Debian, not Alpine: Alpine has no Odia traineddata package.
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
poppler-utils tesseract-ocr tesseract-ocr-ori \
&& rm -rf /var/lib/apt/lists/*
COPY --from=build /pdf2word /usr/local/bin/pdf2word
ENV PORT=8080
EXPOSE 8080
USER nobody
ENTRYPOINT ["sh", "-c", "exec pdf2word -addr 0.0.0.0:$PORT \"$@\"", "--"]Bind to 0.0.0.0, not the 127.0.0.1 default, or the container answers only
itself. Reading $PORT covers Cloud Run, Fly and Render, which all inject it.
Test the parts that can silently rot
Two tests are enough, and both run without a PDF, an image or a copy of Word.
The first feeds a hand-written hOCR fixture through parseHOCR and layout and
asserts the inference: two paragraphs out, lines rejoined into reflowable text,
body text at the median size and not bold, the tall centred line detected as a
heading, the picture region captured.
The second builds a document from two hard-coded paragraphs and unzips it:
b, _ := docx([]para{
{text: "ଓଡ଼ିଆ ଭାଷା & ସାହିତ୍ୟ", sz: 48, bold: true, center: true},
{text: clean("line\x0ctwo"), sz: 24, indent: true, brk: true},
}, "Nirmala UI")
// … unzip, then:
// - all three parts present
// - "ଓଡ଼ିଆ ଭାଷା & ସାହିତ୍ୟ" present, ampersand escaped
// - no 0x0C and no "" anywhere in document.xml
// - w:cs="Nirmala UI" present — without it, Odia renders as boxes
// - <w:b/><w:bCs/>, <w:szCs>, <w:jc>, <w:ind>, <w:br w:type="page"/> all presentThat one string — Odia text, an XML metacharacter and a form feed — is every way this converter has ever produced a file Word refused to open.
What it does not do
Be honest about the ceiling before you point it at a book:
- Tables come out as ordinary paragraphs. hOCR marks cells, but mapping
them onto
w:tblis a project of its own. - Images are dropped. Only the text inside picture regions is recovered, and only if you enable the sparse pass.
- Bold and italic are inferred from height, so an italic aside at body size is indistinguishable from body text.
- Two-column layouts interleave, until you add column clustering.
- OCR errors are OCR errors. A 95% accurate page still has a wrong character every other line, and no amount of layout work fixes that. Budget for a proof- read.
What you do get is a .docx that opens with the chapter headings looking like chapter headings, paragraphs that reflow, page breaks where the book had them, and Odia that renders as Odia — which is a far better starting point for that proof-read than a wall of undifferentiated text.