围绕内联图像框

Frame around inline images

有没有一种方法可以使用 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 格式?

docx目前好像不支持这样的功能。 由于您使用的是 tables,您可能会做以下事情:

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

请阅读 this thread 了解更多详情。

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

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

并将图片添加到 "run"。