Convert HTML to PDF and insert Image with Django

Asked

Viewed 436 times

0

The image does not appear in PDF, I use xhtml2pdf.

reports/sol_access.html

<img src="{% static 'img/small_logo.png' %}" alt="Blue Tech" style="max-width:200px; margin-top:10px">

view py. `

def get(self, request, pk, model):
    projeto = Projeto.objects.select_related('cliente').get(cliente_id=pk)
    try:
        uc = Uc_principal.objects.select_related('cliente').get(cliente_id=pk)
    except Uc_principal.DoesNotExist:
        uc = ''

    context = {
        'projeto': projeto,
        'uc': uc,
    }

    if model == '0':
        pdf = render(request, 'relatorios/sol_acesso.html', context)
        return pdf

    elif model == '1':
        pdf = render_to_pdf('relatorios/sol_acesso.html', context)

    else:
        pdf = render_to_pdf('relatorios/ver_cliente.html', context)

    if pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        filename = "Invoice{}.pdf".format("12341231")
        content = "inline; filename=01_{}".format('Nome')
        download = request.GET.get("download")
        if download:
            content = "attachment; filename=01_{}".format('Nome')
        response['Content-Disposition'] = content
        return response
    return HttpResponse("Not found")

util.py

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("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None 

Detail: If I do not convert to PDF the image appears.

  • Young here at PT.Stackoverflow vc can write in Portuguese, consider translating your question.

  • True, I forgot that I was publishing in pt. kkkkkk

  • 1

    Did you check if it is because the image address is relative? You may have to enter the full address so it doesn’t get lost.

  • @Karlzillner Truth. Putting the full address it appears. Vllw. I’ll see what I can do now.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.