Great observation!
python-docx does not natively support copying images (or tables, or other complex elements) when copying paragraphs. Images in Word documents are usually stored as "inline shapes" or "pictures" within paragraphs or runs, and copying them programmatically is more complex.
Solution: Use docxcompose for Full Content Copy
If you want to preserve images, tables, and all formatting, the best approach is to use the docxcompose library, which can merge entire documents including images and other objects.
Install the required libraries:
pip install python-docx docxcompose
Example: Interleaving Paragraphs with Images
However, docxcompose merges documents end-to-end, not interleaving paragraphs.
To interleave paragraphs and include images, you need to copy the underlying XML elements, not just text and runs.
Below is a solution that copies the full XML of each paragraph, which includes images, and appends it to the new document.
This method works for most images, but may not cover all edge cases (like floating images or certain shapes).
Improved Script: Copy Paragraph XML (with images)
import os
from docx import Document
from copy import deepcopy
def append_paragraph_with_content(paragraph, doc):
# Append the XML of the paragraph (including images) to the doc
new_paragraph = deepcopy(paragraph._element)
doc._body._element.append(new_paragraph)
def combine_docx_files_with_images(original_path, translated_path, output_path):
doc1 = Document(original_path)
doc2 = Document(translated_path)
out_doc = Document()
# Remove the default first empty paragraph
if len(out_doc.paragraphs) == 1 and not out_doc.paragraphs[0].text:
p = out_doc.paragraphs[0]._element
p.getparent().remove(p)
out_doc._body.clear_content()
min_len = min(len(doc1.paragraphs), len(doc2.paragraphs))
for i in range(min_len):
append_paragraph_with_content(doc1.paragraphs[i], out_doc)
append_paragraph_with_content(doc2.paragraphs[i], out_doc)
for i in range(min_len, len(doc1.paragraphs)):
append_paragraph_with_content(doc1.paragraphs[i], out_doc)
for i in range(min_len, len(doc2.paragraphs)):
append_paragraph_with_content(doc2.paragraphs[i], out_doc)
out_doc.save(output_path)
def find_docx_files():
files = [f for f in os.listdir('.') if f.lower().endswith('.docx')]
files = [f for f in files if not f.startswith('~$')] # Exclude temp files
return files
if __name__ == "__main__":
docx_files = find_docx_files()
if len(docx_files) < 2:
print("Not enough .docx files found in the current folder.")
else:
print(f"Using '{docx_files[0]}' as original and '{docx_files[1]}' as translated.")
combine_docx_files_with_images(docx_files[0], docx_files[1], 'combined.docx')
print("Combined document saved as 'combined.docx'.")