Keep Word Image Captions from Getting Lost in Translation

The text of the paragraph containing the image is merely contextual candidate material, not a verified figure caption. Inline and floating figures should be inv

Translating Word documents full of technical figures often leaves captions in the wrong place. A caption that sits right above a picture in Word can end up far from it in the file's XML, and a script can still report it as matched.

This guide is for engineers and localisation teams who script Word processing. It explains why image–caption matching breaks, how inline and floating images differ, and how to flag the cases your tools cannot handle safely.

They do not guarantee results for every real file, so keep your original copies and verify output against the acceptance criteria below before you process important documents.

How do you match image captions during Word translation? The short answer

Match captions only to inline images, flag floating images for manual review, and verify every result against your original file.

Your situationWhat to doWhy
Images are embedded inline in the textMatch each caption to the paragraph that contains the imageInline shapes act like a large character and keep a fixed position in the text
Images are floating with text wrappingLog them as skipped and warn the reviewerTheir position depends on anchors and coordinates, not paragraph order
Your script picks the caption closest to a floating imageDo not use distance-based matching for floating imagesText can wrap around floating images, so spatial closeness is unreliable
Images sit in tables, text boxes or complex layoutsSend them to manual reviewParagraph traversal becomes unreliable in these layouts
An image placeholder appears but no text was extractedKeep the placeholder token and review key diagramsHidden styles or missing OCR can hide the text

Why does your image caption always fail to match?

When you process Word documents with many technical illustrations, the hardest problem is rarely lost images. It is text–image separation.

Consider a common case. The heading in paragraph 5 and the image in paragraph 6 belong to the same figure, yet in the XML they can sit far apart. Worse, your extractor may confidently return “Figure 3: System Architecture” while the matching image is a floating shape. If your parser handles only inline shapes, you may believe the figure was processed when you have actually missed important visual information.

This kind of silent failure does more damage than an explicit error, because nothing tells you to look again.

The two-layer model behind Word

The core of the problem is Word's two-layer model: a text layer and a drawing layer.

  • Inline images sit in the text layer. Like a large character, they have a clear paragraph affiliation and a fixed order relative to the surrounding text.
  • Floating images sit in a separate drawing layer. Their position comes from absolute coordinates or anchors. Being physically close to text does not make them logically bound to it.

Before you write an automation script, check the embedding type of each target image. Then decide whether you can trust the paragraph-index relationships.

Inline shapes and floating objects: the essential difference

What python-docx supports

The python-docx library fully supports reading and writing inline pictures. According to its documentation, inline shapes behave as a single glyph: they expand the line height and move with the text flow. If you iterate through paragraph.runs, you can reliably capture the inline image object, and its index in the list reflects its position in the sentence.

Why floating shapes need separate handling

Floating shapes may look adjacent to a paragraph, but in the DOM tree they are usually nested in containers outside the paragraph or under specific anchor attributes.

If you build a translation or content-extraction pipeline, state the scope explicitly, for example: “This script processes only inline images.” Then:

  • Do not force-match floating images to caption text with heuristics such as “closest distance.” Word lets text wrap around floating images, so spatial relationships are unreliable when you parse plain text.
  • Log the presence of each floating image and raise a warning, rather than producing incorrect associations.

Synthetic example: correct binding and boundary detection

To show how to extract image–text relationships safely, the example uses a synthetic scenario. The input document contains two cases:

  1. The standard “title + inline image + caption” structure.
  2. Interfering elements, including floating images.

Expected output: The program should identify the paragraph containing each inline figure, extract the adjacent caption, and return structured data. For floating figures, it should mark them explicitly as “not supported/skipped” and must not classify them as processed inline figures.

Error and boundary handling: If a user submits a document with only floating images, or with images nested in complex tables or text boxes, the script should neither crash nor return an empty string that looks like success. It should return a result object with a status code such as “Non-inline graphic objects detected; manual review required.” An explicit “not processed” result is more useful than implicit error handling.

The code below demonstrates this defensive approach. It is for instruction only and is not meant to run as-is.

from io import BytesIO
from PIL import Image
from docx import Document
doc = Document()
picture = BytesIO()
Image.new("RGB", (10, 10), "red").save(picture, format="PNG")
picture.seek(0)
paragraph = doc.add_paragraph("Candidate context, not verified caption")
paragraph.add_run().add_picture(picture)
doc.add_paragraph("Unrelated paragraph")
records = []
for index, p in enumerate(doc.paragraphs):
    inline = p._p.xpath(".//wp:inline")
    floating = p._p.xpath(".//wp:anchor")
    if inline or floating:
        records.append({"paragraph": index, "inline_count": len(inline),
                        "floating_count": len(floating), "context_candidate": p.text})
assert len(records) == 1
assert records[0]["inline_count"] == 1
assert records[0]["floating_count"] == 0
assert records[0]["context_candidate"] == "Candidate context, not verified caption"

To run the example, create a new Word document. Insert an inline image with a caption, then insert a second image with tight text wrapping. Save the file as input.docx in the same directory as the script.

The code queries the XML namespaces directly instead of using a high-level wrapper. The python-docx API abstracts floating diagrams only to a limited degree. Inspecting w:drawing for wp:inline and wp:anchor tags is the most dependable way to tell the two apart. The namespace URI is a fixed OOXML standard and does not change between library versions.

Acceptance criteria and manual review boundaries

Before you add such a script to production, define an acceptance matrix. Do not judge it by its automation rate alone. Judge it by how visible its errors are. The table below lists common observations from engineering work, with the automated decision and the trigger for manual review.

ObservationLikely causeAutomated decisionManual review trigger
Image and caption are in the same RunRare format error or non-standard generatorSplit by text, tag with low confidenceReview every such case
Paragraph contains a wp:anchor tagFloating figure with text wrappingRecord the location, return skipped statusFloating figures exceed 10% of the document
Image inside a table cellNested structureExtract normally, but keep cell coordinatesTable spans multiple pages or has merged cells
Several consecutive inline figures with no text between themPuzzle or step screenshotsTreat as one group, merge the explanatory textMore than 3 images and no sequence numbers
Extracted text is empty but an image placeholder existsHidden style or missing OCRKeep the placeholder tokenKey diagram in technical documentation

Where this approach does not apply

This approach suits technical documents that consist mainly of text. It does not work well for posters, brochures and magazine layouts with complex typesetting, where text boxes are heavily linked and positioned absolutely. In those layouts, paragraph traversal stops being effective.

The code also checks only the ability to recognise XML structure. It does not measure end-to-end translation or conversion performance. In real projects, consider other factors too, such as image resolution, colour mode and the language of the captions.

Next steps and references

Run the floating-graphics detection script on your own document set and calculate the share of non-inline graphics. If that share is significant, adjust your parsing strategy or confirm the scope of support with your translation service before you commit to a fully automated workflow.

Use this checklist for document translation

Word translation projects often mix up content problems with formatting problems. Keep checks for styles, headers, tables and other formatting in your delivery checklist, so reviewers know where to look for each kind of issue.

OmniDoc (Product Entry) offers a way to translate documents in several formats.

📊 At a glance

AspectInline imageFloating image
Location in the documentText layer, as a large characterDrawing layer, placed by anchors or coordinates
Paragraph affiliationClearNot reliable from plain text
Support in python-docxRead and writeDetect through wp:anchor in the XML
Caption matchingMatch to the containing paragraphLog as skipped and warn

🎯 Which approach fits you?

If you translate technical manuals with inline figures

Match captions to the paragraph containing each image, and keep the original copies for checking.

If your documents use text wrapping or floating diagrams

Detect floating images, log them as skipped, and route them for manual review.

If your layouts include posters, brochures or heavy text boxes

Paragraph traversal will not be reliable, so plan a manual or specialised workflow.

❓ FAQ

1. Why does my image caption match the wrong image?

Floating images sit in a separate drawing layer, so their XML position can be far from the caption paragraph.

2. Does python-docx handle floating images?

It fully supports inline images. To detect floating images, inspect the wp:inline and wp:anchor tags in the XML.

3. Can my script guess a floating image's caption from the nearest text?

No. Text can wrap around floating images, so the nearest text is not a reliable caption. Log the image and raise a warning instead.

4. Can I use the example code in production?

Keep the originals and verify output against the acceptance criteria first.

📝 Summary

Captions stay matched only when you track the image's embedding type. Treat inline images as bound to their paragraph, flag floating images for review, and verify every result against your original file.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-29