Last modified: Nov 11, 2025 By Alexander Williams

Add and Resize Images in DOCX Using Python

Python-docx makes document automation easy. You can add images to Word documents programmatically. This saves time and ensures consistency.

This guide covers image insertion and resizing techniques. You will learn practical methods with clear examples. Let's explore the powerful image handling capabilities.

Installing Python-docx

First, install the python-docx library. Use pip, the Python package manager. Run this command in your terminal or command prompt.


pip install python-docx

This downloads and installs the latest version. The library is now ready for use. You can import it into your Python scripts.

Basic Image Insertion

Adding images is straightforward with python-docx. Use the add_picture() method. This method belongs to document paragraphs.

Create a new document object first. Then add a paragraph. Finally, call add_picture with your image path.


from docx import Document
from docx.shared import Inches

# Create a new document
doc = Document()

# Add a paragraph
paragraph = doc.add_paragraph()

# Add image to the paragraph
run = paragraph.add_run()
run.add_picture('image.jpg')

# Save the document
doc.save('document_with_image.docx')

The code creates a simple Word document. It inserts your specified image. The document saves with the image included.

Understanding Image Positioning

Images anchor to specific locations in the document. They become part of the paragraph flow. This affects how they move with text.

You can control image placement precisely. Add images to specific paragraphs. Or create dedicated paragraphs for images only.

For advanced layout control, explore Python docx Section Breaks: Advanced Layout Control. This helps with complex document structures.

Image Resizing Methods

Python-docx provides multiple resizing options. You can specify width and height. Or use convenient measurement units.

The most common approach uses Inches or Cm classes. This ensures consistent sizing across documents. Let's examine practical examples.

Resizing with Inches

Use the Inches class for imperial measurements. Import it from docx.shared. Then specify dimensions in inches.


from docx import Document
from docx.shared import Inches

doc = Document()
paragraph = doc.add_paragraph()

# Add image with specific size in inches
run = paragraph.add_run()
picture = run.add_picture('image.jpg', width=Inches(3.0), height=Inches(2.0))

doc.save('resized_image.docx')

The image resizes to exactly 3 inches wide. The height becomes 2 inches. The aspect ratio might distort if not proportional.

Resizing with Centimeters

For metric measurements, use the Cm class. The process is identical to inches. Just import Cm instead.


from docx import Document
from docx.shared import Cm

doc = Document()
paragraph = doc.add_paragraph()

# Add image with specific size in centimeters
run = paragraph.add_run()
picture = run.add_picture('image.jpg', width=Cm(10.0), height=Cm(7.0))

doc.save('resized_image_cm.docx')

The image now measures 10cm by 7cm. Choose the unit system that matches your requirements.

Maintaining Aspect Ratio

Often you want to maintain aspect ratio. Specify only width or height. Python-docx calculates the other dimension automatically.


from docx import Document
from docx.shared import Inches

doc = Document()
paragraph = doc.add_paragraph()

# Maintain aspect ratio by specifying only width
run = paragraph.add_run()
picture = run.add_picture('image.jpg', width=Inches(4.0))

doc.save('proportional_image.docx')

The height adjusts automatically. The original aspect ratio preserves. This prevents image distortion.

Working with Different Image Formats

Python-docx supports common image formats. JPEG, PNG, and BMP work well. The library handles format conversion internally.

Ensure your image files are accessible. Use correct file paths. Relative paths work from your script's location.

For professional documents, consider Generate Invoices in DOCX Using Python. Images often enhance business documents.

Advanced Image Handling

Beyond basic insertion, you can manipulate images further. Access image properties after adding. This enables dynamic adjustments.


from docx import Document
from docx.shared import Inches

doc = Document()
paragraph = doc.add_paragraph()

run = paragraph.add_run()
picture = run.add_picture('image.jpg')

# Access and modify image properties
print(f"Original width: {picture.width}")
print(f"Original height: {picture.height}")

# Resize after insertion
picture.width = Inches(2.5)
picture.height = Inches(1.8)

doc.save('modified_image.docx')

This approach offers flexibility. You can make decisions based on original dimensions. Then apply appropriate resizing logic.

Error Handling and Best Practices

Always implement error handling. Check if image files exist. Handle potential exceptions gracefully.


import os
from docx import Document
from docx.shared import Inches

def add_image_safely(doc, image_path, width=None, height=None):
    if not os.path.exists(image_path):
        print(f"Error: Image file {image_path} not found")
        return None
    
    try:
        paragraph = doc.add_paragraph()
        run = paragraph.add_run()
        
        if width and height:
            return run.add_picture(image_path, width=width, height=height)
        elif width:
            return run.add_picture(image_path, width=width)
        elif height:
            return run.add_picture(image_path, height=height)
        else:
            return run.add_picture(image_path)
            
    except Exception as e:
        print(f"Error adding image: {e}")
        return None

# Usage example
doc = Document()
add_image_safely(doc, 'photo.jpg', width=Inches(3.0))
doc.save('safe_image.docx')

This robust approach prevents crashes. It provides helpful error messages. Your automation becomes more reliable.

Real-World Applications

Image handling has many practical uses. Generate reports with charts and graphs. Create product catalogs with item photos.

Build document templates with placeholder images. Automate certificate generation with logos. The possibilities are extensive.

For academic contexts, see Academic Report Formatting with Python-docx. Images often enhance research papers and reports.

Conclusion

Python-docx provides powerful image capabilities. You can add and resize images programmatically. This enables document automation at scale.

Remember the key methods. Use add_picture() for insertion. Specify dimensions with Inches or Cm classes. Maintain aspect ratio when important.

Implement proper error handling. Test your code with various image formats. Build robust document generation systems.

Start experimenting with these techniques. Automate your Word document creation. Save time and ensure consistency across documents.