Generate a PDF from HTML in Django
Let's install the weasyprint package.
Which, in the case of Windows you must install the following program:
https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer/releases
And on macOS:
$ brew install python pango libffi
On the official website:
https://doc.courtbouillon.org/weasyprint/stable/
You have the details of the programs that you must install to be able to use this package from Python.
Once the dependencies are installed, you can now install the package as one more dependency:
$ pip install weasyprint
Its use is very simple, just use the HTML() function, indicating the URL to which you want to convert into HTML and where you want to write it using the write_pdf() function, in this example, the Google URL is which let's convert to PDF:
pdfs\views.py
from weasyprint import HTML
def generate_pdf(request):
filename="documents/archivo.pdf"
HTML("https://www.google.com.ve/").write_pdf(filename)
return render(request, 'csv.html')
And we will have:
This package allows you to use other options such as indicating the size of the page:
from weasyprint import HTML, CSS
***
HTML(string='''
<h1>The title</h1>
<p>Content goes here
''').write_pdf(filename)
CSS(string='@page { size: A3; margin: 1cm }')
Or define CSS:
HTML('http://weasyprint.org/').write_pdf('/tmp/weasyprint-website.pdf',
stylesheets=[CSS(string='body { font-family: serif !important }')])
You can see all this and more in the official documentation; using this option is particularly useful if the PDF document you want to generate is simple and can be represented by an HTML document; but, many times this is not the case and you need a perfect pixel solution as we will see next.
- Andrés Cruz
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter