【问题标题】:How to display image in python docx template (docxtpl)? Django Python如何在 python docx 模板(docxtpl)中显示图像? Django Python
【发布时间】:2021-07-19 06:07:58
【问题描述】:

我正在使用 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) 中。提前致谢。

【问题讨论】:

    标签: python django image templates python-docx


    【解决方案1】:

    图像必须是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 ...
    

    【讨论】:

      【解决方案2】:

      您当前将变量 foto_web_low 链接到 url,而不是实际图像。您需要先下载图像,然后附加它。下面的代码未经测试,但应该是正确的方向:

      首先,下载图片:

       response = requests.get("https://The_URL_of_the_picture.jpg")
      file = open("the_image.png", "wb")
      file.write(response.content)
      file.close()
      

      然后简单地将图像添加到上下文中的变量中:

      docente= {
         "id":145,
         ...
         "foto_web_low":"the_image.png",
        ...
      }
      

      【讨论】:

        猜你喜欢
        • 2013-04-05
        • 1970-01-01
        • 2011-11-10
        • 1970-01-01
        • 2017-02-16
        • 2013-02-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多