python - 如何在python docx模板(docxtpl)中显示图像? python

标签 python django image templates python-docx

bounty结束了。回答这个问题有资格获得 +50 声望奖励。赏金宽限期将在 17 小时后结束。
Fernando Javier León想引起更多的注意这个问题。







我正在使用 python-docx-template (docxtpl) 生成 .docx文件。
有了这个数据:

docente= {
   "id":145,
   "lugar_de_nacimiento":"Loja",
   "fecha_de_nacimiento":"1973-04-14",
   "ciudad":"Loja",
   "foto_web_low":"https://sica.utpl.edu.ec/media/uploads/docentes/fotos/web/low/1102904313_low.jpg"
}
我有一个函数可以传递图像 docente['foto_web_low']context和模板的路径:
from docxtpl import DocxTemplate, InlineImage
from docx.shared import Mm

def generaraDocumento(request):
    response = HttpResponse(content_type='application/msword')
    response['Content-Disposition'] = 'attachment; filename="cv.docx"'

    doc = DocxTemplate(str(settings.BASE_DIR) + '/cv_api/templates/docx_filename.docx')
    imagen = docente['foto_web_low'] 

    context = {'imagen': imagen}

    doc.render(context)
    doc.save(response)

    return response
我想要显示的图像的模板 docx_filename.docx有这个:
我想要显示的数据的模板 docx_filename.docx有这个:
Image: {{ imagen }} 
生成文档时,我只得到 URL 地址而不是图像,在我的模板中它返回:
Image: https://sica.utpl.edu.ec/media/uploads/docentes/fotos/web/low/1102904313_low.jpg
如何让图像出现在文档中 .docx (docxtpl) .提前致谢。

最佳答案

图像必须是 docxtpl.InlineImage 的实例( see docs )。
另一个重要的事情是图像必须存在于磁盘上。 docxtpl不支持从 url 读取图像。
例子:

from docxtpl import InlineImage
from docx.shared import Mm


doc = DocxTemplate(str(settings.BASE_DIR) + '/cv_api/templates/docx_filename.docx')

# The image must be already saved on the disk
# reading images from url is not supported
imagen = InlineImage(doc, '/path/to/image/file.jpg', width=Mm(20)) # width is in millimetres

context = {'imagen': imagen}

# ... the rest of the code remains the same ...

关于python - 如何在python docx模板(docxtpl)中显示图像? python ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68435780/

相关文章:

Python-BeautifulSoup : find td width

python - 将预测保存到 json 或 txt 文件,并在 yolov3 对象检测中保存输出视频文件 - Google colab

Django:从模板中访问 session 变量?

java - 在 Android 上使用 UDP 进行图像传输

image - 使用数据 URI 方案和 img 标签的攻击

python - Arff 装载机 : AttributeError: 'dict' object has no attribute 'data'

python - 当我从数据框中的一行中创建一个列表时,它在 for 循环中仅迭代一次,而当对列执行相同操作时,它工作得很好

python - 将小时和天添加到 python 日期时间

python - Django - 如何过滤管理页面表中可编辑列中的外键选择?

ios - 在 iOS 中使用 Storyboard将图像设置为 TableView 的背景