Word & layout

Where should the caption for a Word image be placed so it doesn’t get lost?

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

阅读文本 / Reading text
This paper uses synthetic samples to demonstrate the processing method. The code has been verified using examples in an isolated environment; this does not guarantee effectiveness for all real files or products. Before processing important files, please retain the original copies and verify them against the boundaries and acceptance criteria outlined in this document. Which problem does this paper address first The text of the paragraph containing the image is merely contextual candidate material, not a verified figure caption. Inline and floating figures should be inventoried separately; w:drawing and wp:inline belong to different namespaces, and incorrect queries may silently overlook images. self-contained synthetic example dependencies are listed in the import list. The code constructs inputs in memory; runtime logs are provided separately and do not constitute a guarantee for all real-world files. 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" Why does your image caption always fail to match When processing Word documents containing a large number of technical illustrations, the most frustrating issue for engineers is not image loss, but rather “text–image separation.” When you use a script to extract paragraph text, you may find that the heading of paragraph 5 and the image in paragraph 6 are logically part of the same entity, yet in the XML structure they could be far apart; or even worse, the extractor confidently returns “Figure 3: System Architecture,” while the corresponding image is actually a floating object (Floating Shape), and your parser only supports inline shapes (Inline Shape), leading you to mistakenly believe that the figure has been processed, when in fact you have overlooked crucial visual information. This kind of “silent failure” is even more damaging than an outright error. The core to solving this problem lies in understanding Word’s two-layer model: the text layer and the drawing layer. Only when an image is embedded into the text layer as an “inline shape” does it, like a large character, have a definite paragraph affiliation and a specific order relative to the surrounding text. By contrast, floating images reside in a separate drawing layer; their position is determined by absolute coordinates or anchors, and physical adjacency to the text flow does not imply logical binding. Before writing an automation script, one must first verify the embedding type of the target image and then decide whether to trust the current paragraph-indexing relationships. The essential difference between inline shapes and floating objects python-docx The library currently only fully supports read and write operations for inline images (Inline Pictures). According to the official documentation, inline shapes are treated as a single glyph; they expand the line height and move along with the text flow. This means that if we iterate through paragraph.runs , can stably capture the inline image object, and the index of this Run in the list directly reflects its position in the sentence. In contrast, floating shapes may appear visually adjacent to a given paragraph, but in the DOM tree they are typically nested within containers outside the paragraph or under specific anchor attributes. If you are building a document translation or content-extraction pipeline, you must explicitly state: “This script processes only inline images.” For floating images, do not attempt to forcibly match caption text using heuristic rules such as “closest distance,” because Word’s layout engine allows text to wrap around floating images, making such spatial relationships entirely unreliable from a plain-text parsing perspective. The correct approach is to log the presence of floating images and issue a warning, rather than generating incorrect associated data. synthesis example: correct binding and boundary detection To demonstrate how to safely extract the image–text relationship, we construct a synthetic scenario. Suppose the input document contains two types of cases: first, the standard “title + inline image + caption” structure; second, interfering elements that include floating images. is expected to produce the correct output : The program should accurately identify the paragraph containing inline figures, extract the adjacent caption, and return structured data. For floating figures, the program should explicitly mark them as “not supported/skipped,” rather than incorrectly classifying them as processed inline figures. Error/Boundary Input Handling : If the user submits a document containing only floating images, or if images are enclosed within complex nested tables or text boxes, the script should neither crash nor return an empty string to pretend it succeeded. Instead, it should return a result object containing a status code that explicitly indicates, “Non-inline graphic objects detected; manual review required.” This explicit “no processing” approach is more valuable than implicit “error handling.” The following code demonstrates this defensive programming approach. Please note that this example is for instructional purposes and does not run in practice; input.docx To be prepared by the reader: Create a new Word document, insert an “embedded” image and add a caption, then insert another floating image with “tight wrapping,” and save it as input.docx is placed in the same directory as the script. The above code does not use advanced encapsulation; instead, it directly queries the XML namespace. This is because python-docx The high-level API has limited abstraction for floating diagrams, directly inspecting w:drawing under wp:inline and wp:anchor tags are the most reliable means of distinguishing between the two. Note that the namespace URI in the code is a fixed OOXML standard and does not change with library versions. Acceptance Criteria and Manual Review Boundary Before integrating such scripts into the production environment, a clear acceptance matrix must be established. Do not place blind faith in “automation rate”; instead, focus on “error visibility.” The following table lists common observation points and corresponding handling decisions encountered in real-world engineering: Observation of the phenomenon technical attribution automated decision-making Manual review trigger condition image and caption are in the same Run rare format error or non-standard generator is split by text, with low-confidence tags All such cases must be reviewed by paragraph contains wp:anchor tag floating figure/text wrapping records the location, returning skipped status When the proportion of floating diagrams in the document exceeds 10% image inside the table cell nested structure Normal extraction, but retain cell coordinates When a table spans multiple pages or cells are merged Multiple consecutive inline figures with no intervening text puzzle or step screenshot Treated as a single group, with the explanatory text merged. number of images >3 and when there is no sequence number extraction text is empty but there is an image placeholder style hidden or OCR missing retains the placeholder token Key diagram in the technical documentation Scope of Non-Applicability Statement : This solution is applicable only to technical documents that primarily consist of textual content. For posters, brochures, and magazine layouts with complex typesetting—where text boxes are extensively linked and absolute positioning is used—the paragraph-traversal approach becomes entirely ineffective. Furthermore, the code demonstration only verifies the ability to recognize XML structure and does not reflect end-to-end translation or conversion performance. In real-world applications, additional orthogonal considerations must be taken into account, such as the resolution and color mode of images, as well as language detection for accompanying captions. References and Next Steps python-docx: Understanding pictures and other shapes recommends that readers immediately run the floating-graphics detection script on their own corpus to calculate the proportion of non‑inline graphics. If this proportion is significant, they should prioritize adjusting the parsing strategy or confirming the scope of support with the translation service, rather than blindly proceeding with a fully automated workflow. uses this checklist for document translation Word translations often blur the distinction between content issues and formatting problems. Leave checks for styles, headers, tables, and other elements to the delivery checklist, so that reviewers know where to look. OmniDoc (Product Entry) provides an entry point for translating multi-format documents, and the official website highlights its OCR, terminology database, and bilingual alignment features. For teams that wish to start processing directly from files, this is a path worth evaluating with real-world samples. Please use de-identified files that you are authorized to upload, and verify the results against the checklist provided in this document; we do not claim that OmniDoc utilizes the open-source libraries or internal algorithms referenced herein, nor do we substitute examples for product performance testing. - 1 -
Updated 2026-10-09