django 在我的pdf上显示一个图像用render_to_pdf生成

kpbwa7wx  于 2023-02-10  发布在  Go
关注(0)|答案(1)|浏览(109)

我想在我的pdf文件中显示一张我从信息中生成的图像
views.py

class GeneratePdf(View):
    def get(self, request, *args, **kwargs):
       data={'name':'toto','age':122,'service':'smapa'}
       pdf = render_to_pdf('cart/commande.html',data)
       return HttpResponse(pdf, content_type='application/pdf')

utils.py

from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template

from xhtml2pdf import pisa

def render_to_pdf(template_src, context_dict={}):
  template = get_template(template_src)
  html  = template.render(context_dict)
  result = BytesIO()
  pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result)
  if not pdf.err:
     return result.getvalue()
  return None

commande.html

{% load static %}
""
<body>
    <div class='wrapper'>
        <div class='header'>
            <p class='title'>Invoice # </p>
            <img src="{% static 'images/tof.png' %}" style="width:100px;height: 100px;">
        </div>
    <div>
    <div class='details'>
        name: {{name}}<br/>
        age: {{age}} <br/>
        service: {{service}}
        <hr class='hrItem' />
    </div>
</div>
</body>
""

我不能显示图像,在pdf文档的级别上,它是在执行控制台的级别上提到的,
Need a valid file name

vxf3dgd4

vxf3dgd41#

我设法显示图像的pdf格式,通过做:
commande.html

<img src="static/images/tof.png" style="width:100px;height: 100px;">

谢谢

相关问题