DOCX Creation, Editing, and Analysis
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, which you can read or edit. Different tools and workflows are available for different tasks.
Workflow Decision Tree
Read/Analyze Content
Use the "Text Extraction" or "Raw XML Access" sections below
Create New Document
Use the "Create New Word Document" workflow
Edit Existing Document
-
Your own document + simple modifications
Use the "Basic OOXML Editing" workflow
-
Other people's documents
Use the "Redline Annotation Workflow" (recommended default)
-
Legal, academic, business, or government documents
Use the "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 track changes:
bash
# Convert document to markdown while preserving track changes
pandoc --track-changes=all path-to-file.docx -o output.md
# Options: --track-changes=accept/reject/all
Raw XML Access
Raw XML access is required for the following features: comments, complex formatting, document structure, embedded media, and metadata. For these features, you need to unpack the document and read its raw XML content.
Unpack Files
python ooxml/scripts/unpack.py <office_file> <output_directory>
Key File Structure
- - Main document content
- - Comments referenced in document.xml
- - Embedded images and media files
- Track changes uses (insert) and (delete) tags
Create 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 entire file: Read in full from start to finish (about 500 lines). Do not set any scope limits when reading this file. Read the entire file content to understand detailed syntax, key formatting rules, and best practices before starting to create the document.
- Create a JavaScript/TypeScript file using Document, Paragraph, TextRun components (you can assume all dependencies are installed; if not, see the Dependencies section below)
- Export to .docx using Packer.toBuffer()
Edit Existing Word Documents
When editing existing Word documents, use the 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 entire file: Read in full from start to finish (about 600 lines). Do not set any scope limits when reading this file. Read the entire file content to understand the Document Library API and XML schema for direct document file editing.
- Unpack the document:
python ooxml/scripts/unpack.py <office_file> <output_directory>
- Create and run a Python script using the Document Library (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 Annotation Workflow for Document Review
This workflow allows you to implement changes in OOXML after planning comprehensive track changes using markdown. Key: To implement complete track changes, you must systematically implement all modifications.
Batch Processing Strategy: Group related modifications into batches of 3-10 changes. This makes debugging more manageable while maintaining efficiency. Test each batch before moving to the next.
Principle: Minimal, Precise Editing
When implementing track changes, only mark the text that is actually changed. Repeating unchanged text makes edits harder to review and looks unprofessional. Break replacements into: [Unchanged Text] + [Delete] + [Insert] + [Unchanged Text]. Preserve the original RSID of unchanged text by extracting and reusing the original
elements.
Example - Changing "30 days" to "60 days" in a sentence:
python
# Wrong - Replace entire 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>'
# Correct - Only mark changed parts, preserve unchanged text with original <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>'
Track Changes Workflow
-
Get markdown representation: Convert the document to markdown with track changes preserved:
bash
pandoc --track-changes=all path-to-file.docx -o current.md
-
Identify and group modifications: Review the document and identify all required changes, organizing them into logical batches:
Localization Methods (for finding modifications in XML):
- Chapter/title 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 XML structure
Batch Organization (group 3-10 related changes per batch):
- By chapter: "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 document and unpack:
- Required - Read the entire file: Read in full from start to finish (about 600 lines). Do not set any scope limits when reading this file. Pay special attention to the "Document Library" and "Track Changes Mode" sections.
- Unpack the document:
python ooxml/scripts/unpack.py <file.docx> <dir>
- Note the suggested RSID: The unpack script will suggest an RSID for track changes. Copy this RSID for step 4b.
-
Implement modifications in batches: Group changes logically (by chapter, type, or proximity) and implement them together in a single script. This approach:
- Makes debugging easier (smaller batches = easier to isolate errors)
- Allows incremental progress
- Maintains efficiency (batch size of 3-10 changes works well)
Suggested Batch Groupings:
- By document chapter (e.g., "Section 3 Modifications", "Definitions", "Termination Clauses")
- By modification type (e.g., "Date Modifications", "Party Name Updates", "Legal Term Replacements")
- By proximity (e.g., "Modifications on Pages 1-3", "Modifications in First Half of Document")
For each batch of related modifications:
a. Map text to XML: Use Grep in
to verify how text is split across
elements.
b. Create and run script: Use
to find nodes, implement modifications, then
. See patterns in the
"Document Library" section of ooxml.md.
Note: Always grep
immediately before writing the script to get current line numbers and verify text content. Line numbers change after each script run.
-
Pack the document: After all batches are complete, convert the unpacked directory back to .docx:
bash
python ooxml/scripts/pack.py unpacked reviewed-document.docx
-
Final Verification: Perform a comprehensive check of the complete document:
- Convert the final document to markdown:
bash
pandoc --track-changes=all reviewed-document.docx -o verification.md
- Verify all modifications are correctly applied:
bash
grep "original phrase" verification.md # Should not find anything
grep "replacement phrase" verification.md # Should find it
- Check for unintended modifications
Convert Documents to Images
To visualize and analyze Word documents, use a two-step process to convert them to images:
-
Convert DOCX to PDF:
bash
soffice --headless --convert-to pdf document.docx
-
Convert PDF Pages to JPEG Images:
bash
pdftoppm -jpeg -r 150 document.pdf page
This will create files like
,
, etc.
Options:
- : Set resolution to 150 DPI (adjust based on quality/size balance)
- : Output in JPEG format (use if PNG is preferred)
- : First page to convert (e.g., starts from page 2)
- : Last page to convert (e.g., stops at page 5)
- : Prefix for output files
Example for specifying a range:
bash
pdftoppm -jpeg -r 150 -f 2 -l 5 document.pdf page # Convert only pages 2-5
Code Style Guide
Important: When generating DOCX manipulation code:
- Write concise code
- Avoid lengthy variable names and redundant operations
- Avoid unnecessary print statements
Dependencies
Required dependencies (install if not available):
- pandoc:
sudo apt-get install pandoc
(for text extraction)
- docx: (for creating new documents)
- LibreOffice:
sudo apt-get install libreoffice
(for PDF conversion)
- Poppler:
sudo apt-get install poppler-utils
(for pdftoppm to convert PDF to images)
- defusedxml: (for secure XML parsing)