问题
Is there a way to put frames around inline images with python docx?
I have something like:
from docx import Document
from docx.shared import Mm
document = Document()
table = document.add_table(rows=1, cols=3)
pic_cells = table.rows[0].cells
paragraph = pic_cells[0].paragraphs[0]
run = paragraph.add_run()
run.add_picture('testQR.png', width=Mm(15), height=Mm(15))
document.save('demo.docx')
I need to put a frame around the image to mark the border of this image (that should be identical with the image size).
How can I format this with the python docx package?
回答1:
It seems that docx currently has no support for such a feature.
Since you are using tables, what you probably could do is the following:
- Create new Word template
- Define custom table style with the border for a cell where you are going to place your image
- Use the template in your Python script with
docxlike this:document = Document('template.docx') - Apply table style you've just created
Please, read this thread for more details.
Another approach could be less elegant, but 100% working. You just create a border around an image before you use it in docx.
You can use PIL (for python2) or Pillow (for pyhton3) module for the image manipulation.
from PIL import Image
from PIL import ImageOps
img = Image.open('img.png')
img_with_border = ImageOps.expand(img, border=1, fill='black')
img_with_border.save('img-with-border.png')
This code will take your img.png file and create a new img-with-border.png outlined with a 1px black border. Just use img-with-border.png in you run.add_picture statement then.
回答2:
As mentioned by vrs in comments, the simplest solution is :
table = document.add_table(rows=5, cols=2, style="Table Grid")
and add picture to the "run".
来源:https://stackoverflow.com/questions/34555705/frame-around-inline-images