Recently I've used the tutorial from YT and other websites on how to convert HTML to PDF in Django. But it didn't work with the images.
Views.py
from django.shortcuts import render
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from django.views import View
from xhtml2pdf import pisa
#Generates PDF
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
data = {
"company": "Dennnis Ivanov Company",
"address": "123 Street name",
"city": "Vancouver",
"state": "WA",
"zipcode": "98663",
"phone": "555-555-2345",
"email": "[email protected]",
"website": "dennisivy.com",
}
#Opens up page as PDF
class ViewPDF(View):
def get(self, request, *args, **kwargs):
pdf = render_to_pdf('html_to_pdf/pdf_template.html', data)
return HttpResponse(pdf, content_type='application/pdf')
I've looked for many StackOverflow posts as well as many docs, but as I'm just beginning in Django I don't understand how to solve this problem(I'm not the only one). I hope someone can modify this code and explain it clearly why it doesn't work.
I'm loading images in pdf_template.html using
<img src="{% static "html_to_pdf/images/img.jpg" %}" alt="My image">
Django 3.0.8
Python 3.6.3