我使用python-docx-template (docxtpl)来生成一个.docx
文件。使用此数据:
docente= {
"id":145,
"cedula":"1102904313",
"primer_apellido":"Salcedo",
"segundo_apellido":"Viteri",
"primer_nombre":"Karina",
"segundo_nombre":"Soledad",
"lugar_de_nacimiento":"Loja",
"fecha_de_nacimiento":"1973-04-14",
"ciudad":"Loja",
"direccion":"Juan Montalvo 2235 y George Washington",
"telefono_institucion":"072570275",
"email_principal":"kssalcedo@utpl.edu.ec",
"foto_web_low":"https://sica.utpl.edu.ec/media/uploads/docentes/fotos/web/low/1102904313_low.jpg",
"nacionalidad":"Ecuatoriana",
"pais_de_residencia":"Ecuador",
"apellido":"Salcedo Viteri",
"nombre":"Karina Soledad"
}
我有一个函数,将数据docente
传递给context
和模板的路径:
from docxtpl import DocxTemplate
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')
context = {'docente': docente}
doc.render(context)
doc.save(response)
return response
我想要显示docx_filename.docx
的数据所在的模板具有以下内容:
{{ docente.foto_web_low }}
{{docente.nombre}} {{docente.apellido}}
Fecha de Nacimiento: {{docente.fecha_de_nacimiento}}
Lugar de Nacimiento: {{docente.lugar_de_nacimiento}}
Dirección: {{docente.direccion}}
Teléfono: {{docente.telefono_institucion}}
Correo: {{docente.email_principal}}
Nacionalidad: {{docente.nacionalidad}}
Cédula: {{docente.cedula}}
我的字段{{ docente.foto_web_low }}
有一个图像所在的url,但在生成文件时,它只显示URL而不显示图像。如何使图像出现在document .docx
中如何在python docx模板(docxtpl)中显示图像。提前谢谢。
发布于 2021-12-07 09:44:36
图像必须是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 ...
发布于 2021-11-29 10:40:38
您当前将变量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",
...
}
https://stackoverflow.com/questions/68435780
复制相似问题