Python

Create Quick And Dirty PDFs from Web Pages in Python

Let’s say you want to make a script that creates a PDF of a web page. pdfkit makes that pretty easy. Simply import pdfkit and then call pdfkit.from_url, passing along the source location as your first parameter and the resultant file as your second, as follows, using http://docs.jamf.com/10.10.1/jamf-pro/release-notes/What’s_New_in_This_Release.html as our source and just calling the pdf we create Release_Notes.pdf:

import pdfkit pdfkit.from_url('https://docs.jamf.com/10.10.1/jamf-pro/release-notes/What's_New_in_This_Release.html', 'Release_Notes.pdf')

Your source location could also be from a standard html file (e.g. if you’re running from your site location) and for those you’d use pdfkit.from_file instead of pdfkit.from_url. If you don’t have pdfkit installed, you might need to pip it first:

pip install pdfkit

One last note, you can also change a few options you can pass pdfkit for job processing: page-size, margin-top, margin-left, margin-right, and margin-bottom:

import pdfkit myoptions = { 'page-size': 'A4', 'margin-top': '1in', 'margin-left': '1in', 'margin-right': '1in', 'margin-bottom': '1in', } pdfkit.from_url('https://docs.jamf.com/10.10.1/jamf-pro/release-notes/What's_New_in_This_Release.html', 'Release_Notes.pdf',options=myoptions)

When I’ve used options, things always seem to take a long time and a lot more resources to run, so I don’t any more. But that’s just me…