Reputation: 1132
I try to generate a pdf file from an html template in my django app.
First i install library:
pip install --pre xhtml2pdf
then i create in my project folder an utiils.py file with this function:
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("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
i create my html template and then in my views.py file i create the class:
from yourproject.utils import render_to_pdf #created in step 4
class GeneratePdf(View):
def get(self, request, *args, **kwargs):
data = {
'today': datetime.date.today(),
'amount': 39.99,
'customer_name': 'Cooper Mann',
'order_id': 1233434,
}
pdf = render_to_pdf('pdf/invoice.html', data)
return HttpResponse(pdf, content_type='application/pdf')
at this point in my urls.py i add the url for start pdf creation
from idocuments.views import GeneratePdf
...
url(r'^fatt_doc/(?P<fat_num>\w+)/$', GeneratePdf),
but when i start my app and open the link i get an error:
init() takes 1 positional argument but 2 were given
I think the problem is in my urls.py but someone can help me to know how i can call the function for generate pdf from an url?
So many thanks in advance
Upvotes: 1
Views: 1667
Reputation: 334
Use as_view() after the class name.
url(r'^fatt_doc/(?P<fat_num>\w+)/$', GeneratePdf.as_view()),
Upvotes: 1