Overview
Users may ask you to create, edit, or analyze the content of .docx files. A .docx file is essentially a ZIP archive containing XML files and other resources that you can read or edit. You have different tools and workflows available for different tasks.
Workflow Decision Tree
Reading/Analyzing Content
Use the "Text Extraction" or "Raw XML Access" sections below
Creating New Documents
Use the "Creating a New Word Document" workflow
Editing Existing Documents
- Your own document + simple modifications Use the "Basic OOXML Editing" workflow
-
Someone else's document Use "Redline Annotation Workflow"(recommended default)
-
Legal, academic, business, or government documents Use "Redline Annotation Workflow"(required)
Reading and Analyzing Content
Text Extraction
If you only need to read the text content of a document, you should use pandoc to convert the document to markdown. Pandoc preserves document structure well and can display revision tracking:
# 将文档转换为 markdown 并保留修订追踪
pandoc --track-changes=all path-to-file.docx -o output.md
# 选项:--track-changes=accept/reject/all
Raw XML Access
The following features require raw XML access: comments, complex formatting, document structure, embedded media, and metadata. For these features, you need to unpack the document and read its raw XML content.
Unpacking Files
python ooxml/scripts/unpack.py <office_file> <output_directory>
Key File Structure
word/document.xml- Main document contentword/comments.xml- Comments referenced in document.xmlword/media/- Embedded images and media files- Revision tracking uses
<w:ins>(insertion) and<w:del>(deletion) tags
Creating a New Word Document
When creating a new Word document from scratch, use docx-js, which allows you to create Word documents using JavaScript/TypeScript.
Workflow
- Required - Read the file in full: Read
docx-js.mdin full from beginning to end (approximately 500 lines).Never set any range limits when reading this file. Before starting to create a document, read the file contents in full to understand the detailed syntax, key formatting rules, and best practices. - Create a JavaScript/TypeScript file using the Document, Paragraph, and TextRun components (you can assume all dependencies are installed; if not, refer to the Dependencies section below)
- Export to .docx using Packer.toBuffer()
Editing Existing Word Documents
When editing an existing Word document, use Document library(a Python library for OOXML manipulation). This library automatically handles infrastructure setup and provides document manipulation methods. For complex scenarios, you can access the underlying DOM directly through this library.
Workflow
- Required - Read the file in full: Read
ooxml.mdin full from beginning to end (approximately 600 lines).Never set any range restrictions when reading this file. Read the file contents in full to understand the Document library API and the XML schema for directly editing document files. - Unpack the document:
python ooxml/scripts/unpack.py <office_file> <output_directory> - Use the Document library to create and run a Python script (see the "Document library" section in ooxml.md)
- Pack the final document:
python ooxml/scripts/pack.py <input_directory> <office_file>
The Document library provides high-level methods for common operations and direct DOM access for complex scenarios.
Redline comment workflow for document review
This workflow allows you to implement the modifications in OOXML after planning comprehensive tracked changes using markdown.Key: To implement complete tracked changes, you must systematically implement all modifications.
Batching strategy: Group related modifications into batches of 3-10 modifications. This makes debugging more manageable while maintaining efficiency. Test each batch before moving on to the next batch.
Principle: Minimal, precise edits
When implementing tracked changes, only mark the text that actually changed. Repeating unchanged text makes edits harder to review and looks unprofessional. Break replacements down into: [unchanged text] + [deletion] + [insertion] + [unchanged text]. By extracting the original <w:r> elements and reusing them, preserve the original RSID of the unchanged text.
Example - changing "30 days" to "60 days" in a sentence:
# 错误 - 替换整个句子
'<w:del><w:r><w:delText>The term is 30 days.</w:delText></w:r></w:del><w:ins><w:r><w:t>The term is 60 days.</w:t></w:r></w:ins>'
# 正确 - 只标记更改的部分,保留原始 <w:r> 的未更改文本
'<w:r w:rsidR="00AB12CD"><w:t>The term is </w:t></w:r><w:del><w:r><w:delText>30</w:delText></w:r></w:del><w:ins><w:r><w:t>60</w:t></w:r></w:ins><w:r w:rsidR="00AB12CD"><w:t> days.</w:t></w:r>'
Tracked changes workflow
-
Get markdown representation: Convert the document to markdown while preserving tracked changes:
pandoc --track-changes=all path-to-file.docx -o current.md -
Identify and group modifications: Review the document and identify all required modifications, organizing them into logical batches:
Locating methods(for finding modifications in XML):
- Section/heading numbers (e.g. "Section 3.2", "Article IV")
- Paragraph identifiers (if numbered)
- Grep patterns using unique surrounding text
- Document structure (e.g. "first paragraph", "signature block")
- Do not use markdown line numbers - they do not correspond to the XML structure
Batch organization(group 3-10 related modifications per batch):
- By section: "Batch 1: Section 2 revisions", "Batch 2: Section 5 updates"
- By type: "Batch 1: Date corrections", "Batch 2: Party name changes"
- By complexity: Start with simple text replacements, then handle complex structural changes
- By order: "Batch 1: Pages 1-3", "Batch 2: Pages 4-6"
-
Read the document and unpack:
- Must - read the file in full: Read
ooxml.mdin full from beginning to end (about 600 lines).Never set any range restrictions when reading this file. Pay special attention to the "Document library" and "Tracked changes schema" sections. - Unpack the document:
python ooxml/scripts/unpack.py <file.docx> <dir> - Note the suggested RSID: The unpack script will suggest an RSID for tracked changes. Copy this RSID for use in step 4b.
- Must - read the file in full: Read
-
Implement modifications in batches: Group modifications logically (by section, by type, or by proximity), and implement them together in a single script. This approach:
- Make debugging easier (smaller batches = easier to isolate errors)
- Allow incremental progress
- Maintain efficiency (batches of 3-10 changes work well)
Suggested batch grouping:
- By document section (e.g., "Section 3 changes", "Definitions", "Termination clause")
- By change type (e.g., "Date changes", "Party name updates", "Legal term replacements")
- By nearby location (e.g., "Changes on pages 1-3", "Changes in the first half of the document")
For each batch of related changes:
a. Map the text to XML: In
word/document.xmluse Grep to verify how the text is split across<w:r>elements.b. Create and run the script: Use
get_nodeto find the node, implement the modification, thendoc.save(). See the "Document library" section in ooxml.md for the pattern.Note: Before writing the script, always immediately grep
word/document.xmlto get the current line numbers and verify the text content. Line numbers change after each script run. -
Package the document: After all batches are complete, convert the unpacked directory back to .docx:
python ooxml/scripts/pack.py unpacked reviewed-document.docx -
Final verification: Perform a comprehensive check on the complete document:
- Convert the final document to markdown:
pandoc --track-changes=all reviewed-document.docx -o verification.md - Verify that all modifications were applied correctly:
grep "original phrase" verification.md # 应该找不到 grep "replacement phrase" verification.md # 应该找到 - Check whether unintended modifications were introduced
- Convert the final document to markdown:
Convert the document to images
To visually analyze a Word document, use a two-step process to convert it to images:
-
Convert DOCX to PDF:
soffice --headless --convert-to pdf document.docx -
Convert PDF pages to JPEG images:
pdftoppm -jpeg -r 150 document.pdf pageThis will create files such as
page-1.jpg、page-2.jpg.
Options:
-r 150: Set the resolution to 150 DPI (adjust based on the quality/size tradeoff)-jpeg: Output JPEG format (if PNG is preferred, use-png)-f N: The first page to convert (e.g.,-f 2to start from page 2)-l N: The last page to convert (e.g.,-l 5to stop at page 5)page: Prefix for the output file
Example of specifying a range:
pdftoppm -jpeg -r 150 -f 2 -l 5 document.pdf page # 只转换第 2-5 页
Code style guide
Important: When generating DOCX manipulation code:
- Write concise code
- Avoid verbose variable names and redundant operations
- Avoid unnecessary print statements
Dependencies
Required dependencies (install if unavailable):
- pandoc:
sudo apt-get install pandoc(for text extraction) - docx:
npm install -g docx(for creating new documents) - LibreOffice:
sudo apt-get install libreoffice(for PDF conversion) - Poppler:
sudo apt-get install poppler-utils(for pdftoppm converting PDF to images) - defusedxml:
pip install defusedxml(for safe XML parsing)