Skip to content

Instantly share code, notes, and snippets.

@jonperron
Created December 19, 2016 16:07
Show Gist options
  • Save jonperron/6b925796b727536edbd41d48367b62be to your computer and use it in GitHub Desktop.
Save jonperron/6b925796b727536edbd41d48367b62be to your computer and use it in GitHub Desktop.
Simplest way to generate PDF with Weasyprint (http://weasyprint.readthedocs.io) and a Web Framework. I use Django, but it can be surely used with others + jinja for templating. First, render an HTML page as string, then generate the pdf and serve it as response.
from weasyprint import HTML
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="your_pdf.pdf"'
html_out = str(render(request,"mock_page.html",locals()))
html_out = html_out.replace('Content-Type: text/html; charset=utf-8','')
# base_url is used to locate the CSS file
HTML(string=html_out,base_url = request.build_absolute_uri()).write_pdf(response)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment