CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-docx

Create, read, and update Microsoft Word .docx files.

Pending
Overview
Eval results
Files

images-shapes.mddocs/

Images and Shapes

Image insertion and inline shape management with sizing, positioning, and format controls. Provides comprehensive support for adding and manipulating visual elements in documents.

Capabilities

Image Insertion

Add images to documents with flexible sizing and format options.

class Document:
    def add_picture(self, image_path_or_stream, width=None, height=None):
        """Add an image to the document.
        
        Args:
            image_path_or_stream (str or file-like): Path to image file or file-like object
            width (Length, optional): Image width (maintains aspect ratio if height not specified)
            height (Length, optional): Image height (maintains aspect ratio if width not specified)
            
        Returns:
            InlineShape: New inline shape containing the image
        """

class Run:
    def add_picture(self, image_path_or_stream, width=None, height=None):
        """Add an inline picture to the run.
        
        Args:
            image_path_or_stream (str or file-like): Path to image file or file-like object
            width (Length, optional): Picture width
            height (Length, optional): Picture height
            
        Returns:
            InlineShape: New inline shape object
        """

Usage Examples:

from docx.shared import Inches, Cm

# Add image to document with automatic sizing
doc.add_picture('photo.jpg')

# Add image with specific width (height auto-calculated)
doc.add_picture('photo.jpg', width=Inches(2))

# Add image with specific dimensions
doc.add_picture('photo.jpg', width=Inches(3), height=Inches(2))

# Add image from file-like object
with open('image.png', 'rb') as image_file:
    doc.add_picture(image_file, width=Cm(5))

# Add image to specific run
para = doc.add_paragraph('Text with image: ')
run = para.add_run()
run.add_picture('icon.png', width=Inches(0.5))
para.add_run(' more text after image.')

Inline Shape Management

Access and manage inline shapes collection in documents.

class Document:
    @property
    def inline_shapes(self):
        """Collection of all inline shapes in document.
        
        Returns:
            InlineShapes: Collection of inline shape objects
        """

class InlineShapes:
    def add_picture(self, image_path_or_stream, width=None, height=None):
        """Add a picture as an inline shape.
        
        Args:
            image_path_or_stream (str or file-like): Image file path or stream
            width (Length, optional): Picture width
            height (Length, optional): Picture height
            
        Returns:
            InlineShape: New picture inline shape
        """
    
    def __len__(self):
        """Number of inline shapes in collection."""
    
    def __iter__(self):
        """Iterate over inline shapes."""
    
    def __getitem__(self, index):
        """Access inline shape by index."""

Usage Examples:

# Access inline shapes collection
shapes = doc.inline_shapes

# Add picture through shapes collection
shape = shapes.add_picture('diagram.png', width=Inches(4))

# Count and iterate through shapes
print(f"Document has {len(shapes)} inline shapes")

for i, shape in enumerate(shapes):
    print(f"Shape {i}: {shape.type} ({shape.width} x {shape.height})")

# Access specific shape
first_shape = shapes[0]
print(f"First shape type: {first_shape.type}")

Inline Shape Properties

Properties and methods for individual inline shapes.

class InlineShape:
    @property
    def width(self):
        """Shape width (read/write).
        
        Returns:
            Length: Shape width
        """
    
    @width.setter
    def width(self, value):
        """Set shape width."""
    
    @property
    def height(self):
        """Shape height (read/write).
        
        Returns:
            Length: Shape height
        """
    
    @height.setter
    def height(self, value):
        """Set shape height."""
    
    @property
    def type(self):
        """Shape type.
        
        Returns:
            WD_INLINE_SHAPE_TYPE: Type of inline shape
        """

Usage Examples:

from docx.shared import Inches
from docx.enum.shape import WD_INLINE_SHAPE_TYPE

# Add and modify shape
shape = doc.add_picture('image.jpg', width=Inches(2))

# Check shape type
if shape.type == WD_INLINE_SHAPE_TYPE.PICTURE:
    print("This is a picture shape")

# Resize shape
shape.width = Inches(3)
shape.height = Inches(2)

# Get current dimensions
print(f"Shape dimensions: {shape.width.inches}\" x {shape.height.inches}\"")

# Maintain aspect ratio when resizing
original_ratio = shape.width / shape.height
shape.width = Inches(4)
shape.height = Inches(4 / original_ratio)

Image Format Support

Python-docx supports various image formats with automatic format detection.

Supported Formats:

  • JPEG (.jpg, .jpeg) - Most common format for photographs
  • PNG (.png) - Best for images with transparency or crisp graphics
  • BMP (.bmp) - Windows bitmap format
  • GIF (.gif) - Graphics Interchange Format
  • TIFF (.tif, .tiff) - Tagged Image File Format

Usage Examples:

# Add images of different formats
doc.add_picture('photo.jpg', width=Inches(3))        # JPEG
doc.add_picture('logo.png', width=Inches(2))         # PNG with transparency
doc.add_picture('diagram.bmp', width=Inches(4))      # BMP
doc.add_picture('animation.gif', width=Inches(2))    # GIF (first frame)
doc.add_picture('scan.tiff', width=Inches(5))        # TIFF

# Format is automatically detected from file content
# No need to specify format explicitly

Advanced Image Operations

More complex image manipulation and positioning.

Usage Examples:

# Create image with calculated dimensions
from docx.shared import Inches

# Add image and store reference
image_shape = doc.add_picture('chart.png')

# Calculate new size maintaining aspect ratio
original_width = image_shape.width
original_height = image_shape.height
aspect_ratio = original_width / original_height

# Resize to fit specific width
target_width = Inches(5)
target_height = target_width / aspect_ratio

image_shape.width = target_width
image_shape.height = target_height

# Add multiple images in a paragraph
para = doc.add_paragraph()
para.add_run('Before image ')
para.add_run().add_picture('small1.png', width=Inches(0.5))
para.add_run(' between images ')
para.add_run().add_picture('small2.png', width=Inches(0.5))  
para.add_run(' after images.')

# Add images with text wrapping (inline only in python-docx)
para = doc.add_paragraph('This paragraph contains an inline image ')
run = para.add_run()
run.add_picture('inline_image.png', width=Inches(1))
para.add_run(' that flows with the text like any other character.')

Image Loading from Different Sources

Load images from various sources including files, URLs, and byte streams.

Usage Examples:

import io
import requests
from docx import Document
from docx.shared import Inches

# Load from file path
doc.add_picture('/path/to/image.jpg', width=Inches(3))

# Load from file object
with open('image.png', 'rb') as img_file:
    doc.add_picture(img_file, width=Inches(2))

# Load from URL (download first)
response = requests.get('https://example.com/image.jpg')
image_stream = io.BytesIO(response.content)
doc.add_picture(image_stream, width=Inches(2.5))

# Load from bytes
with open('image.gif', 'rb') as f:
    image_bytes = f.read()
    
image_stream = io.BytesIO(image_bytes)
doc.add_picture(image_stream, width=Inches(1.5))

# Create image from base64 data
import base64

base64_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
image_data = base64.b64decode(base64_data)
image_stream = io.BytesIO(image_data)
doc.add_picture(image_stream, width=Inches(0.1))

Shape Positioning and Layout

Control image positioning within document flow.

Usage Examples:

# Images are always inline in python-docx (flow with text)
# For layout control, use paragraph formatting

# Center an image
para = doc.add_paragraph()
para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
para.add_run().add_picture('centered_image.png', width=Inches(4))

# Right-align an image
para = doc.add_paragraph()
para.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
para.add_run().add_picture('right_image.png', width=Inches(3))

# Image with caption
img_para = doc.add_paragraph()
img_para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
img_para.add_run().add_picture('chart.png', width=Inches(5))

caption_para = doc.add_paragraph('Figure 1: Sales Chart')
caption_para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
caption_para.runs[0].italic = True

# Image in table cell for positioning
table = doc.add_table(rows=1, cols=2)
text_cell = table.cell(0, 0)
text_cell.text = "Description text here"

image_cell = table.cell(0, 1)
image_para = image_cell.paragraphs[0]
image_para.add_run().add_picture('product.jpg', width=Inches(2))

Error Handling

Handle common image-related errors and exceptions.

Usage Examples:

from docx.image.exceptions import UnrecognizedImageError
import os

def add_image_safely(doc, image_path, width=None):
    """Add image with error handling."""
    try:
        # Check if file exists
        if not os.path.exists(image_path):
            print(f"Image file not found: {image_path}")
            return None
            
        # Add image
        shape = doc.add_picture(image_path, width=width)
        print(f"Successfully added image: {image_path}")
        return shape
        
    except UnrecognizedImageError:
        print(f"Unsupported image format: {image_path}")
        return None
    except Exception as e:
        print(f"Error adding image {image_path}: {e}")
        return None

# Usage
shape = add_image_safely(doc, 'photo.jpg', width=Inches(3))
if shape:
    print(f"Image added with dimensions: {shape.width} x {shape.height}")

Types

from docx.enum.shape import WD_INLINE_SHAPE_TYPE

class WD_INLINE_SHAPE_TYPE:
    """Inline shape type options."""
    CHART = 3
    LINKED_PICTURE = 5
    PICTURE = 1
    SMART_ART = 15

# Image-related exceptions
from docx.image.exceptions import InvalidImageStreamError, UnexpectedEndOfFileError, UnrecognizedImageError

class InvalidImageStreamError(Exception):
    """Raised when image stream is invalid or corrupted."""

class UnexpectedEndOfFileError(Exception):
    """Raised when image file ends unexpectedly."""

class UnrecognizedImageError(Exception):
    """Raised when image format is not recognized or supported."""

Install with Tessl CLI

npx tessl i tessl/pypi-python-docx

docs

comments.md

document-operations.md

images-shapes.md

index.md

sections-layout.md

styles-formatting.md

tables.md

text-paragraphs.md

tile.json