Inserting and Styling Images in Your Document
When working on a document, there are times when you need to insert images to help convey the content more intuitively.
Using python-docx, you can programmatically insert images into a document and adjust their size and position.
In this lesson, we will learn how to insert and resize images in your document.
Inserting an Image
To insert an image into your document, use the add_picture() method.
This method takes the file path as an argument and adds the image to the document.
doc.add_picture('image.png')
The code above inserts the 'image.png' file into the document.
The image file path can be specified using a relative path or an absolute path.
Resizing an Image
After inserting an image, you can use the Inches or Cm classes to resize it.
This is useful for adjusting the width or height of an image to the desired size.
from docx.shared import Inches doc.add_picture('image.png', width=Inches(2))
The code above sets the width of the image to 2 inches when inserting it into the document.
If the height is not specified, it will be automatically adjusted to maintain the aspect ratio.
doc.add_picture('image.png', width=Inches(2), height=Inches(3))
This example sets the width to 2 inches and the height to 3 inches when inserting the image.
Can We Precisely Adjust the Image Position?
With python-docx, you cannot precisely position an image in terms of how far from the top or left it should appear.
Therefore, if precise image positioning is needed, it is best to insert the image programmatically first and then manually adjust its position by opening the Word file.
Lessons in this chapter ยท How to automate repetitive PowerPoint and Word tasks using Python code
- 1. How to Automate Repetitive PowerPoint Tasks
- 2. Adding Text Box and Text to Slides
- 3. Changing Font, Size, and Color of Text Formatting
- 4. Inserting and Adjusting Images on a Slide
- 5. Creating and Managing Tables in Slides
- 6. Inserting Excel Data into a Slide as a Table
- 7. Creating Charts and Visualizing Data with Python
- 8. Fill-in-the-blank quiz
- 9. Create Word Documents with Python Code
- 10. Adding and Formatting Paragraphs
- 11. Creating Lists
- 12. How to Create Tables with Python Code
- 13. Inserting and Styling Images in Your Document
- 14. Adjusting Document Page Layout
- 15. Read Excel with openpyxl & Write to Word
- 16. Multiple-choice quiz
- 17. Challenge Yourself! Creating a Simple Table with python-docx
Using python-docx, you can insert images into a document.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help