围绕内嵌图像构图 [英] Frame around inline images

查看:68
本文介绍了围绕内嵌图像构图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 python docx 在嵌入式图像周围放置框架?

Is there a way to put frames around inline images with 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')

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

I need to put a frame around the image to mark the border of this image (that should be identical with the image size).

如何使用python docx包格式化该格式?

How can I format this with the python docx package?

推荐答案

似乎 docx 当前不支持此功能.由于您正在使用表,因此您可能会执行以下操作:

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

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

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

此代码将获取您的 img.png 文件,并创建一个轮廓为1px黑色边框的新的 img-with-border.png .只需在 run.add_picture 语句中使用 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.

这篇关于围绕内嵌图像构图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆