Frame around inline images

て烟熏妆下的殇ゞ 提交于 2021-01-28 23:44:44

问题


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:

  1. Create new Word template
  2. Define custom table style with the border for a cell where you are going to place your image
  3. Use the template in your Python script with docx like this: document = Document('template.docx')
  4. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!