djangoqr-codexhtml2pdf

How to show generated QR Code in generated PDF Django


I want to show generated qr code in my generated PDF but it doesn't show. If in html it's showed but not in pdf. I want to show qrcode in PDF without save it to media

Here is my code in views.py :

path_qr = 'localhost:8000/qrcode/detail/1'
qr = QRCode()
qr.add_data(path_qr)
img = qr.make_image()

data = {
  'qr_code': img
}

template = get_template(template_src)
html = template.render(data)
result = BytesIO()
pdf1 = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)

return HttpResponse(result.getvalue(), content_type='application/pdf')

And here is my code in html:

<img src="{{ qrcode }}" width="100" height="100">

Solution

  • I've found the solution. I have to encode into b64. and its work

    dataurl = 'data:image/png;base64,' + b64encode(qr_rend.getvalue()).decode('ascii')
    

    so my code will be like this:

    path_qr = 'localhost:8000/qrcode/detail/1'
    
    qr_rend = BytesIO()
    img = make(path_qr)
    img.save(qr_rend, 'PNG')
    dataurl = 'data:image/png;base64,' + b64encode(qr_rend.getvalue()).decode('ascii')
    

    and in html like this:

    <img src="{{ dataurl }}" width="100" height="100">