Reputation: 184
I want to generate pdf from html in django using xhtml2pdf. But xhtml2pdf seems to make a PDF of full HTML template. What I want to say is that suppose I have a side menu, a header, a footer and a table of some contents in my html file. Now, I want to only generate pdf of that table from the html file. How can I do that using xhtml2pdf ?
Thank you.
Upvotes: 1
Views: 805
Reputation: 1531
You can separate your template files for different part of the page. For example, you may have a base html that contains the common templates, and you will also have your table.html
that contains the data you want to convert to pdf.
You can use include
built-in templatetag to use it in another template: See docs here. You can aslo check extends
templatetag which is very handy here.
Something like this:
# base.html
{% include 'table.html' %}
# views.py
def render_to_pdf(request):
template_path = 'table.html' # Here is the template you want to convert
context = {'myvar': 'this is your template context'}
# Create a Django response object, and specify content_type as pdf
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="report.pdf"'
# find the template and render it.
template = get_template(template_path)
html = template.render(Context(context))
# create a pdf
pisaStatus = pisa.CreatePDF(
html, dest=response, link_callback=link_callback)
# if error then show some funy view
if pisaStatus.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
You can see the pdf creation in xhtml2pdf docs here
Upvotes: 1