Skip to content

Edoardo Vignati

– Always looking for something awesome –

Menu
  • About me
  • Studies
  • Publications
  • Skills
  • Portfolio
  • Projects
  • Career
  • Blog
Menu

Export HTML to PDF with Python and Flask

Posted on 30/03/202230/03/2022 by Edoardo

Here is a very quick guide to generated a PDF from HTML and download it using Flask.

First of all add these two dependencies in you requirements.txt file and install them using pip

pdfkit==1.0.0
wkhtmltopdf==0.2

Then install the pdf engine running:

sudo apt install wkhtmltopdf

In your code, import pdfkit and render an HTML template. Then put the output into pdfkit and return the PDF as following:

import pdfkit

@app.route("/download")
def route_download():
	
	# Get the HTML output
    out = render_template("export.html")
    
    # PDF options
    options = {
        "orientation": "landscape",
        "page-size": "A4",
        "margin-top": "1.0cm",
        "margin-right": "1.0cm",
        "margin-bottom": "1.0cm",
        "margin-left": "1.0cm",
        "encoding": "UTF-8",
    }
    
    # Build PDF from HTML 
    pdf = pdfkit.from_string(out, options=options)
    
    # Download the PDF
    return Response(pdf, mimetype="application/pdf")

You can assign a download filename adding the following header to the Response

headers = {"Content-Disposition": "attachment;filename=myname.pdf"}
return Response(pdf, mimetype="application/pdf", headers=headers)

Troubleshooting

  • Cannot find wkhtmltopdf executable
OSError: No wkhtmltopdf executable found

In this case you have to install wkhtmltopdf:

$ sudo apt install wkhtmltopdf
  • Protocol error
Exit with code 1 due to network error: ProtocolUnknownError

In this case you are not using the http or https protocols in some HTML references, for example in an image tag. To fix this error try to specify the entire URL starting from protocol.

<img src="/myimg.png"> # Wrong
<img src="https://myurl.me/static/images/myimg.png"> # Ok

If you want to render the full URL dynamically via Flask you can add edit your code as following:

from urllib.parse import urlparse

# <img src="{{root}}/static/images/myimg.png">
parsed_url = urlparse(request.url)
root= parsed_url.scheme + "://" + parsed_url.netloc
out = render_template("export.html", root=root)

References

  • https://pypi.org/project/pdfkit/
  • https://docs.python.org/3/library/urllib.parse.html


Buy Me A Coffee


This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  1. Edoardo on [SOLVED] XMLHttpRequest error in Flutter web is a CORS error06/01/2023
  2. Fabi on [SOLVED] XMLHttpRequest error in Flutter web is a CORS error20/12/2022
  3. Edoardo on How to install hplip on Ubuntu28/11/2022
  4. Alex K on How to install hplip on Ubuntu28/11/2022

© 2023 Edoardo Vignati | Powered by Minimalist Blog WordPress Theme
Manage Cookie Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Manage options Manage services Manage vendors Read more about these purposes
View preferences
{title} {title} {title}