How to create pdf files in Python using Pdfkit

pip install pdfkit
import pdfkit
pdfkit.from_url('http://micropyramid.com', 'micro.pdf')
import pdfkit
pdfkit.from_file('micropyramid.html', 'micro.pdf')
import pdfkit
pdfkit.from_string('MicroPyramid', 'micro.pdf')
options = {
'page-size': 'A4',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
}
pdfkit.from_url('http://micropyramid.com', 'micro.pdf', options=options)
from django.template.loader import get_template 
from django.template import Context
import pdfkit
template = get_template("output_pdf.html")
context = Context({"data": data}) # data is the context data that is sent to the html file to render the output.
html = template.render(context) # Renders the template with the context data.
pdfkit.from_string(html, 'out.pdf')
pdf = open("out.pdf")
response = HttpResponse(pdf.read(), content_type='application/pdf') # Generates the response as pdf response.
response['Content-Disposition'] = 'attachment; filename=output.pdf'
pdf.close()
os.remove("out.pdf") # remove the locally created pdf file.
return response # returns the response.
wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-amd64.tar.bz2
tar xvjf wkhtmltopdf-0.9.9-static-amd64.tar.bz2
sudo mv wkhtmltopdf-amd64 /usr/local/bin/wkhtmltopdf
sudo chmod +x /usr/local/bin/wkhtmltopdf

The article was originally published at MicroPyramid blog.

--

--

--

Python, Django, Android and IOS, reactjs, react-native, AWS, Salesforce consulting & development company

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Elasticsearch: Building Autocomplete with Go (Completion Suggester)

Bad Go: not sizing slices

One day, you’re questioning what on earth will ever make you feel happy and fulfilled

Installing nvm via brew on High Sierra

My Topconf Linz 2017 Retrospective

Remote Procedure Calls

Learn Unity Game Development Bundle

Builder Design Pattern example

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
MicroPyramid

MicroPyramid

Python, Django, Android and IOS, reactjs, react-native, AWS, Salesforce consulting & development company

More from Medium

Build a Desktop-Based Weather App using Python

Build a Free Python Flask Website on Heroku

Create a simple to-do list app with Python Flask and Vue.js. Part 2

How to Receive WhatsApp messages using python and webhook