内联图像边框

2024-04-19 16:38:19 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以用python docx在内联图像周围放置边框?在

我有这样的东西:

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')

我需要在图像周围放置一个边框来标记此图像的边框(这应该与图像大小相同)。在

如何用python docx package格式化它?在


Tags: runfrom图像importaddtabledocumentrows
2条回答

似乎docx当前不支持这样的功能。 由于您使用的是表,因此您可能需要执行以下操作:

  1. 新建Word模板
  2. 为要放置图像的单元格定义带边框的自定义表格样式
  3. 将Python脚本中的模板与docx一起使用,如下所示:document = Document('template.docx')
  4. 应用刚创建的表格样式

请阅读this thread了解更多详细信息。在

另一种方法可能不那么优雅,但100%有效。在使用docx之前,只需在图像周围创建一个边框。 您可以使用PIL(对于python2)或Pillow(对于python3)模块来进行图像操作。在

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')

这段代码将获取您的img.png文件,并创建一个新的img-with-border.png,用1px的黑色边框勾勒。只需在run.add_picture语句中使用img-with-border.png。在

正如vrs在评论中提到的,最简单的解决方案是:

table = document.add_table(rows=5, cols=2, style="Table Grid")

并在“跑步”中添加图片。在

相关问题 更多 >