Skip to main content

Async Python-PDFKit: HTML to PDF wrapper

Build Status PyPI version PyPI pyversions

Python 3.5+ async wrapper for wkhtmltopdf utility to convert HTML to PDF using Webkit.

NOTE: All the public API functions are adapted to async coroutines, so use them with await!


This is adapted version of ruby PDFKit library, so big thanks to them!

Installation

  1. Install python-pdfkit:
$ pip install pdfkit-async
  1. Install wkhtmltopdf:

    • Windows and other options: check wkhtmltopdf homepage for binary installers

    • Debian/Ubuntu:

    $ sudo apt-get install wkhtmltopdf
    
    • macOS:
    $ brew install caskroom/cask/wkhtmltopdf
    

Warning! Version in debian/ubuntu repos have reduced functionality (because it compiled without the wkhtmltopdf QT patches), such as adding outlines, headers, footers, TOC etc. To use this options you should install static binary from wkhtmltopdf site or you can use this script.

Usage

For simple tasks:

import pdfkit

async def f():
    await pdfkit.from_url('http://google.com', 'out.pdf')
    await pdfkit.from_file('test.html', 'out.pdf')
    await pdfkit.from_string('Hello!', 'out.pdf')

You can pass a list with multiple URLs or files:

await pdfkit.from_url(['google.com', 'yandex.ru', 'engadget.com'], 'out.pdf')
await pdfkit.from_file(['file1.html', 'file2.html'], 'out.pdf')

Also you can pass an opened file:

with open('file.html') as f:
    await pdfkit.from_file(f, 'out.pdf')

If you wish to further process generated PDF, you can read it to a variable:

# Use False instead of output path to save pdf to a variable
pdf = await pdfkit.from_url('http://google.com', False)

You can specify all wkhtmltopdf options. You can drop '--' in option name. If option without value, use None, False or '' for dict value:. For repeatable options (incl. allow, cookie, custom-header, post, postfile, run-script, replace) you may use a list or a tuple. With option that need multiple values (e.g. --custom-header Authorization secret) we may use a 2-tuple (see example below).

options = {
    'page-size': 'Letter',
    'margin-top': '0.75in',
    'margin-right': '0.75in',
    'margin-bottom': '0.75in',
    'margin-left': '0.75in',
    'encoding': "UTF-8",
    'custom-header' : [
        ('Accept-Encoding', 'gzip')
    ]
    'cookie': [
        ('cookie-name1', 'cookie-value1'),
        ('cookie-name2', 'cookie-value2'),
    ],
    'no-outline': None
}

await pdfkit.from_url('http://google.com', 'out.pdf', options=options)

By default, PDFKit will show all wkhtmltopdf output. If you don't want it, you need to pass quiet option:

options = {
    'quiet': ''
    }

await pdfkit.from_url('google.com', 'out.pdf', options=options)

Due to wkhtmltopdf command syntax, TOC and Cover options must be specified separately. If you need cover before TOC, use cover_first option:

toc = {
    'xsl-style-sheet': 'toc.xsl'
}

cover = 'cover.html'

await pdfkit.from_file('file.html', options=options, toc=toc, cover=cover)
await pdfkit.from_file('file.html', options=options, toc=toc, cover=cover, cover_first=True)

You can specify external CSS files when converting files or strings using css option.

Warning This is a workaround for this bug in wkhtmltopdf. You should try --user-style-sheet option first.

# Single CSS file
css = 'example.css'
await pdfkit.from_file('file.html', options=options, css=css)

# Multiple CSS files
css = ['example.css', 'example2.css']
await pdfkit.from_file('file.html', options=options, css=css)

You can also pass any options through meta tags in your HTML:

body = """
    <html>
      <head>
        <meta name="pdfkit-page-size" content="Legal"/>
        <meta name="pdfkit-orientation" content="Landscape"/>
      </head>
      Hello World!
      </html>
    """

await pdfkit.from_string(body, 'out.pdf') #with --page-size=Legal and --orientation=Landscape

Configuration

Each API call takes an optional configuration paramater. This should be an instance of pdfkit.configuration() API call. It takes the configuration options as initial paramaters. The available options are:

  • wkhtmltopdf - the location of the wkhtmltopdf binary. By default pdfkit will attempt to locate this using which (on UNIX type systems) or where (on Windows).
  • meta_tag_prefix - the prefix for pdfkit specific meta tags - by default this is pdfkit-

Example - for when wkhtmltopdf is not on $PATH:

config = pdfkit.configuration(wkhtmltopdf='/opt/bin/wkhtmltopdf')

await pdfkit.from_string(html_string, output_file, configuration=config)

Troubleshooting

  • IOError: 'No wkhtmltopdf executable found':

    Make sure that you have wkhtmltopdf in your $PATH or set via custom configuration (see preceding section). where wkhtmltopdf in Windows or which wkhtmltopdf on Linux should return actual path to binary.

  • IOError: 'Command Failed'

    This error means that PDFKit was unable to process an input. You can try to directly run a command from error message and see what error caused failure (on some wkhtmltopdf versions this can be cause by segmentation faults)

Changelog

  • 0.7.2

    • Fixed Project description for latest rules
    • Fixed Travis build
    • Updated README
  • 0.7.0

    • Dropped support of Python2.7 till Python3.4
    • Supports Python3.5+
    • AsyncIO support
    • Project took over by shivanshs9
  • 0.6.1

    • Fix regression on python 3+ when trying to decode pdf output
  • 0.6.0

    • Support repeatable options
    • Support multiple values for some options
    • Fix some corner cases when specific argument order is required
    • Some Python 3+ compatibility fixes
    • Update README
  • 0.5.0

    • Allow passing multiple css files
    • Fix problems with external file encodings
    • Rise an error when X server is missing on *nix systems
    • Fix tests that was broken with latest wkhtmltopdf release
    • Update README
  • 0.4.1

    • More easier custom configuration setting
    • Update README
  • 0.4.0

    • Allow passing file-like objects
    • Ability to return PDF as a string
    • Allow user specification of configuration
    • API calls now returns True on success
    • bugfixes
  • 0.3.0

    • Python 3 support
  • 0.2.4

    • Add History
    • Update setup.py
  • 0.2.3

    • Fix installing with setup.py
    • Update README

Metadata

Release files for pdfkit-async 0.7.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pdfkit-async 0.7.2
File Size Uploaded Provenance Actions
pdfkit-async-0.7.2.tar.gz 12.9 kB Without provenance Details for pdfkit-async-0.7.2.tar.gz

Release files / pdfkit-async-0.7.2.tar.gz

Download URL pdfkit-async-0.7.2.tar.gz
Size 12.9 kB
Tags Source
SHA-256 checksum
How to use checksums
ef623ccd1ecfeb1f4bd16a556a6bbb6218102cb41053c80bad37cb51474336a4
BLAKE2b-256 checksum
How to use checksums
c231a27a83ab997d8ec303d953520506116c913d42109618c424cfa50bd72dba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.1.3 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.8.2

Security for pdfkit-async 0.7.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.7.2 This release

1 release file No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page