3 Ways to Insert Images into Word Documents with Python

Alice Yang
7 min readJun 12, 2024

--

The adage “a picture is worth a thousand words” holds true in the realm of document creation. By strategically placing relevant images within your Word documents, you can break up dense text, provide visual context, and ultimately improve the reader’s understanding of the content. This is particularly valuable when conveying complex ideas or presenting intricate data. In this article, we will explore how to insert images into Word documents using Python.

We will discuss the following topics:

Python Library to Insert Images into Word Documents

To insert images into Word documents with Python, we can use the Spire.Doc for Python library.

Spire.Doc for Python is a feature-rich and easy-to-use library for creating, reading, editing, and converting Word files within Python applications. With this library, you can work with a wide range of Word formats, including Doc, Docx, Docm, Dot, Dotx, Dotm, and more. Moreover, you are also able to render Word documents to other types of file formats, such as PDF, RTF, HTML, Text, Image, SVG, ODT, PostScript, PCL, and XPS.

You can install Spire.Doc for Python from PyPI by running the following command in your terminal:

pip install Spire.Doc

For more detailed information about the installation, you can check this official documentation: How to Install Spire.Doc for Python in VS Code.

Insert an Inline Image into a Word Document with Python

Inline images are the most common type of image insertion in Microsoft Word. When you insert an inline image, it becomes part of the text flow, meaning it will move along with the surrounding paragraphs as you edit the document. This method is ideal for images that are meant to be integrated into the body of your text, such as illustrating a specific point or breaking up longer sections of content.

To insert an inline image into a Word document using Python, follow these key steps:

  • Create a new Document object.
  • Add a section using Document.AddSection() function.
  • Add a paragraph using Section.AddParagraph() function.
  • Add an image to the paragraph using Paragraph.AppendPicture() function.
  • Set width, height and text wrapping style for the image.
  • Save the result to a file using Document.SaveToFile() function.

Here is a simple example of inserting an inline image into a Word document in Python:

from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
document = Document()
# Add a section
section = document.AddSection()
# Set page margins
section.PageSetup.Margins.All = 72

# Add a title paragraph to the section
title_paragraph = section.AddParagraph()
# Set text and format for the paragraph
text_range = title_paragraph.AppendText("Introduction to Python Programming Language")
text_range.CharacterFormat.FontName = "Calibri"
text_range.CharacterFormat.TextColor = Color.get_RoyalBlue()
title_paragraph.ApplyStyle(BuiltinStyle.Heading1)
title_paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
title_paragraph.Format.AfterSpacing = 18

# Add a content paragraph to the section
content_paragraph = section.AddParagraph()
# Set text and format for the paragraph
text_range = content_paragraph.AppendText("Python is a powerful and versatile programming language that has become increasingly popular in recent years. It is an interpreted, high-level language known for its simplicity, readability, and ease of use, making it an excellent choice for beginners and experienced developers alike. Python's clean and concise syntax, combined with its extensive standard library and support for multiple programming paradigms, allow programmers to be highly productive and efficiently tackle a wide range of tasks, from web development and data analysis to machine learning and scientific computing. With its cross-platform compatibility, large and active community, and constantly-expanding ecosystem of third-party libraries and tools, Python has solidified its position as one of the most widely-used and influential programming languages in the world.")
text_range.CharacterFormat.FontName = "Calibri"
text_range.CharacterFormat.FontSize = 12
content_paragraph.Format.HorizontalAlignment = HorizontalAlignment.Justify

# Add an image to the content paragraph
image = content_paragraph.AppendPicture("Python.png")
# Set image width and height
image.Width = 100
image.Height = 100
# Set text wrapping style for the image
image.TextWrappingStyle = TextWrappingStyle.Square

# Save the document to a file
try:
document.SaveToFile("AddInlineImage.docx", FileFormat.Docx2019)
document.Close()
except Exception as e:
print(f"Error saving document: {e}")
Add Inline Image to Word with Python
Add Inline Image to Word with Python

Insert an Absolutely Positioned Image into a Word Document with Python

In contrast to inline images, absolutely positioned images in Microsoft Word are placed independently of the surrounding text. These images maintain a fixed position on the page, allowing you to layer them on top of text or position them in specific locations. Absolute positioning is particularly useful for creating visual callouts, overlaying images on diagrams or charts, or inserting watermarks or decorative elements that should remain stationary regardless of text edits.

To insert an absolutely positioned image into a Word document using Python, follow these key steps:

  • Create a new Document object.
  • Add a section using Document.AddSection() function.
  • Add a paragraph using Section.AddParagraph() function.
  • Add an image to the paragraph using Paragraph.AppendPicture() function.
  • Set width, height and text wrapping style for the image.
  • Set horizontal and vertical origins for the image using DocPicture.HorizontalOrigin and DocPicture.VerticalOrigin properties.
  • Set absolute horizontal and vertical positions for the image using DocPicture.HorizontalPosition and DocPicture.VerticalPosition properties.
  • Set horizontal and vertical alignment for the image using DocPicture.HorizontalAlignment and DocPicture.VerticalAlignment properties.
  • Save the result to a file using Document.SaveToFile() function.

Here is a simple example of inserting an absolutely positioned image into a Word document in Python:

from spire.doc import *
from spire.doc.common import *

try:
# Create a Document object
document = Document()

# Add a section
section = document.AddSection()

# Set page margins
section.PageSetup.Margins.All = 72.0

# Add a title paragraph to the section
title_paragraph = section.AddParagraph()
# Set text and format for the paragraph
text_range = title_paragraph.AppendText("Introduction to Python Programming Language")
text_range.CharacterFormat.FontName = "Calibri"
text_range.CharacterFormat.TextColor = Color.get_RoyalBlue()
title_paragraph.ApplyStyle(BuiltinStyle.Heading1)
title_paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
title_paragraph.Format.AfterSpacing = 18

# Add a paragraph to the section
paragraph = section.AddParagraph()

# Add an image to the paragraph
image = paragraph.AppendPicture("Python.png")
# Set image width and height
image.Width = 100
image.Height = 100
# Set text wrapping style for the image (note when the text wrapping style is inline, the images are not absolutely positioned)
image.TextWrappingStyle = TextWrappingStyle.Square

# Set horizontal and vertical origin for the image
image.HorizontalOrigin = HorizontalOrigin.Page
image.VerticalOrigin = VerticalOrigin.Paragraph

# Set absolute horizontal and vertical position for the image
image.HorizontalPosition = 200
image.VerticalPosition = 150
# Set horizontal and vertical alignment for the image
image.HorizontalAlignment = ShapeHorizontalAlignment.Center
image.VerticalAlignment = ShapeVerticalAlignment.Center

# Save the document to a file
document.SaveToFile("AddAbsolutelyPositionedImage.docx", FileFormat.Docx2019)
print("Document saved successfully.")
document.Close()
except Exception as e:
print(f"Error processing the document: {e}")
Add Absolutely Positioned Image to Word with Python
Add Absolutely Positioned Image to Word with Python

Insert an Image into Each Page of a Word Document with Python

Inserting an image to appear on every page of your Microsoft Word document can be a powerful way to establish a consistent visual theme or branding throughout your content. This technique is often used for inserting logos or other recurring elements that should be present on all pages.

To insert an image into each page of a Word document using Python, follow these key steps:

  • Create a new Document object.
  • Load an existing Word document using Document.LoadFromFile() function.
  • Create a FixedLayoutDocument object for converting the document to a fixed layout document.
  • Get the pages of the document using FixedLayoutDocument.Pages property.
  • Iterate through the pages.
  • For each page, get a specific line on the page using FixedLayoutPage.GetChildEntities() function, and then get the paragraph of the line using FixedLayoutLine.Paragraph property.
  • Add an image to the paragraph using Paragraph.AppendPicture() function.
  • Set width, height, text wrapping style, horizontal and vertical origins, positions and alignments for the image.
  • Save the result to a file using Document.SaveToFile() function.

Here is a simple example of inserting an image into each page of a Word document in Python:

from spire.doc import *
from spire.doc.common import *

try:
# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("AI.docx")

# Create an object of the FixedLayoutDocument class to convert the document to a fixed layout document
layoutDoc = FixedLayoutDocument(document)
# Get the pages of the document
pages = layoutDoc.Pages

# Iterate through the pages of the document
for page_index in range(pages.Count):
page = pages[page_index]
# Get the lines of the page
lines = page.GetChildEntities(LayoutElementType.Line, True)
if lines:
# Get the paragraph of the first line
paragraph = lines[0].Paragraph
# Add an image to the paragraph
image = paragraph.AppendPicture("Logo2.png")
# Set image width and height
image.Width = 100
image.Height = 100
# Set text wrapping style for the image
image.TextWrappingStyle = TextWrappingStyle.Behind

# Set horizontal and vertical origin for the image
image.HorizontalOrigin = HorizontalOrigin.Page
image.VerticalOrigin = VerticalOrigin.Paragraph

# Set absolute horizontal and vertical position for the image
image.HorizontalPosition = 200
image.VerticalPosition = 150
# Set horizontal and vertical alignment for the image
image.HorizontalAlignment = ShapeHorizontalAlignment.Center
image.VerticalAlignment = ShapeVerticalAlignment.Center

# Save the document to a file
document.SaveToFile("AddImageToEachPage.docx", FileFormat.Docx2019)
print("Document saved successfully.")
document.Close()
except Exception as e:
print(f"Error processing the document: {e}")
Add Image to Each Page in Word with Python
Add Image to Each Page in Word with Python

Conclusion

This article demonstrated three different scenarios for inserting images into Word documents using Python. We hope you find it helpful.

Related Topics

Useful Links

Spire.Doc for Python Documentation | Free License | Forum

--

--

Alice Yang

Skilled senior software developers with five years of experience in all phases of software development life cycle using .NET, Java and C++ languages.