Batch DOCX Conversion: A Safe CLI and Automation Workflow

November 08, 2026 · DOCX.now Editorial · DOCX Essentials

Design a repeatable DOCX batch process with canaries, logs, validation and rollback.

Canary Pre-Conversion Validation

Before any conversion engine touches a file, verify structural integrity against the ZIP-based Office Open XML container format. A three-point check catches malformed or mislabeled files that pass trivial extension filters:

canary_check() {
  local file="$1"
  # Verify ZIP magic bytes (PK\x03\x04)
  if [[ $(xxd -l 2 -p "$file") != "504b" ]]; then
    echo "FAIL: Not a ZIP archive" >&2
    return 1
  fi
  # Confirm [Content_Types].xml at archive root
  if ! unzip -l "$file" | grep -q "[Content_Types].xml"; then
    echo "FAIL: Missing [Content_Types].xml" >&2
    return 1
  fi
  # Confirm word/document.xml exists
  if ! unzip -l "$file" | grep -q "word/document.xml"; then
    echo "FAIL: Missing word/document.xml" >&2
    return 1
  fi
  return 0
}

This sequence rejects approximately 95% of corrupt or mislabeled files before conversion. Files passing all three checks but failing during conversion typically contain deeply nested XML errors or unsupported custom XML schemas in word/_rels/. Log these separately as degraded failures.

Conversion Engine Hard Limits

Two CLI engines handle batch DOCX conversion reliably. Each has documented boundaries per the ECMA-376 specification referenced in MS-DOCX.

Pandoc 3.x Structural Limits

Pandoc parses paragraph styles, inline formatting, and basic tables. It does not process:

  • Tracked changes (revisions) — silently dropped
  • Embedded fonts or font substitution rules stored in word/fontTable.xml
  • OMML (Office Math Markup Language) equations — only LaTeX-style math converts
  • Custom XML elements in the w:customXml namespace
  • Content control data bindings (w:dataBinding)

Python-docx 1.1.x Extraction Limits

Python-docx handles paragraph, run, and section properties. It cannot process:

  • VML (Vector Markup Language) drawing objects in word/vmlDrawing*.vml
  • ActiveX controls or embedded macros stored in word/vbaProject.bin
  • Complex field codes referencing nonexistent headings or bookmarks
  • Alternate content blocks (mc:AlternateContent) with multiple fallback branches

Three-Stage Conversion Pipeline

Stage 1: Enumeration and Locking

Generate a sorted manifest and acquire per-file locks to prevent concurrent writes:

find ./input -name "*.docx" -type f | sort > batch_manifest.txt
while IFS= read -r file; do
  lockfile="${file}.lock"
  if ! mkdir "$lockfile" 2>/dev/null; then
    echo "SKIP: $file (in use)" >> conversion.log
    continue
  fi
  echo "$file" >> processing_queue.txt
done < batch_manifest.txt

Hard limit: 10,000 files per manifest. Beyond this, split into subdirectories of 5,000 files each to avoid argument list overflow in downstream commands.

Stage 2: Conversion with Structured Logging

Each invocation must emit a single JSON line containing input path, output path, engine version, status, byte sizes, and a warnings array:

{
  "timestamp": "2025-01-15T14:32:01Z",
  "input": "/data/invoices/INV-2024-09.docx",
  "output": "/data/converted/INV-2024-09.md",
  "status": "passed",
  "input_size": 45821,
  "output_size": 12403,
  "engine": "pandoc 3.6",
  "warnings": ["dropped: 2 tracked changes"]
}

Capture stderr from the conversion engine and append it to the warnings array. Never truncate warnings — they are the primary diagnostic for degraded output.

Stage 3: Output Validation and Rollback

Validate output before deleting the original DOCX. For text-based output, apply minimum byte threshold and structural checks:

validate_output() {
  local output="$1"
  local min_bytes="$2"
  if [[ ! -f "$output" ]]; then
    echo "FAIL: No output file produced" >&2
    return 1
  fi
  local actual_size=$(wc -c < "$output")
  if (( actual_size < min_bytes )); then
    echo "FAIL: Output too small ($actual_size < $min_bytes)" >&2
    return 1
  fi
  # Check for unbalanced Markdown code fences
  if grep -c '```' "$output" | awk '{if($1%2!=0) exit 1}'; then
    echo "FAIL: Unbalanced code fences" >&2
    return 1
  fi
  return 0
}

On validation failure, move the output to ./quarantine/ and preserve the original DOCX. This is the rollback mechanism: re-run the batch targeting only quarantined files after diagnosing the root cause.

Failure Classification and Logging

Maintain three separate log files:

Log File Contents
conversion.log One JSON line per file attempt with status and warning count
failures_detailed.log Full stderr for every failed conversion
canary_failures.log Files rejected during pre-conversion validation

Classify each failure into one of three buckets:

  • Recoverable: Missing media references in word/_rels/document.xml.rels, corrupt ZIP central directory. Rebuild with zip -F and retry.
  • Degraded: Output produced but with dropped tracked changes, comments, or OMML equations. Log warnings, mark status as degraded, proceed.
  • Unrecoverable: Corrupt word/document.xml, encrypted DOCX with password protection, files containing EncryptedPackage stream. Route to manual review.

Automation Integration

For cron or CI/CD scheduling, wrap the pipeline in a script that exits with the count of unrecoverable failures:

#!/bin/bash
set -euo pipefail

BATCH_DIR="/data/docx_batch"
CANARY_DIR="${BATCH_DIR}/canary_logs"
CONVERTED_DIR="${BATCH_DIR}/converted"
QUARANTINE_DIR="${BATCH_DIR}/quarantine"

mkdir -p "$CANARY_DIR" "$CONVERTED_DIR" "$QUARANTINE_DIR"

# Stage 1: Canary checks
find "$BATCH_DIR/input" -name "*.docx" -type f | while read file; do
  canary_check "$file" || echo "$file" >> "$CANARY_DIR/rejected_$(date +%Y%m%d).txt"
done

# Stages 2-3: Convert and validate
while IFS= read -r file; do
  convert_with_logging "$file" "$CONVERTED_DIR" "$QUARANTINE_DIR"
done < <(comm -23 <(find "$BATCH_DIR/input" -name "*.docx" | sort) \
                  <(cat "$CANARY_DIR"/*.txt 2>/dev/null | sort))

ERRORS=$(grep -c '"status":"failed"' "$BATCH_DIR/conversion.log" 2>/dev/null || echo 0)
exit "$ERRORS"

When Batch Automation Is Not Appropriate

Stop and route files to manual review when:

  • DOCX files contain embedded macros in word/vbaProject.bin or ActiveX controls that must survive conversion
  • Files reference custom XML schemas in word/_rels/ with namespace declarations incompatible with the target format
  • Input spans multiple DOCX versions with conflicting namespace prefixes (Word 2003 compatibility mode w: vs. Word 365 w14: namespaces in the same batch)

In these cases, the quarantine directory becomes the input queue for manual triage. Do not attempt automated conversion on files matching these criteria.