Top Related Projects
Convert HTML to PDF using Webkit (QtWebKit)
The awesome document factory
Laravel Snappy PDF
PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. Wrapper for wkhtmltopdf/wkhtmltoimage
Quick Overview
Python-PDFKit is a wrapper for the wkhtmltopdf tool, allowing users to generate PDFs from HTML content using Python. It provides a simple and convenient way to create PDF documents from web pages or HTML strings, making it useful for report generation, document conversion, and web scraping tasks.
Pros
- Easy to use with a straightforward API
- Supports both local HTML files and remote URLs
- Offers a wide range of configuration options for PDF output
- Can be integrated with web frameworks like Django and Flask
Cons
- Requires wkhtmltopdf to be installed separately
- May have rendering inconsistencies compared to browser output
- Limited support for complex JavaScript-heavy pages
- Performance can be slow for large or complex HTML documents
Code Examples
- Converting a URL to PDF:
import pdfkit
pdfkit.from_url('https://www.example.com', 'output.pdf')
- Converting an HTML string to PDF:
import pdfkit
html_content = '<h1>Hello, World!</h1><p>This is a test.</p>'
pdfkit.from_string(html_content, 'output.pdf')
- Converting multiple HTML files to a single PDF:
import pdfkit
pdfkit.from_file(['file1.html', 'file2.html'], 'output.pdf')
- Using configuration options:
import pdfkit
options = {
'page-size': 'Letter',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
}
pdfkit.from_url('https://www.example.com', 'output.pdf', options=options)
Getting Started
-
Install wkhtmltopdf:
- On Ubuntu:
sudo apt-get install wkhtmltopdf
- On macOS:
brew install wkhtmltopdf
- For other systems, download from: https://wkhtmltopdf.org/downloads.html
- On Ubuntu:
-
Install python-pdfkit:
pip install pdfkit
-
Basic usage:
import pdfkit # Convert URL to PDF pdfkit.from_url('https://www.example.com', 'output.pdf') # Convert HTML file to PDF pdfkit.from_file('input.html', 'output.pdf') # Convert HTML string to PDF html_content = '<h1>Hello, World!</h1>' pdfkit.from_string(html_content, 'output.pdf')
Competitor Comparisons
Convert HTML to PDF using Webkit (QtWebKit)
Pros of wkhtmltopdf
- Standalone command-line tool, can be used without Python
- More flexible and feature-rich, offering advanced PDF rendering options
- Supports a wider range of input formats, including HTML, CSS, and JavaScript
Cons of wkhtmltopdf
- Requires separate installation and system dependencies
- Can be more complex to set up and use for simple PDF generation tasks
- May have performance overhead for basic use cases
Code Comparison
wkhtmltopdf (command-line usage):
wkhtmltopdf http://example.com output.pdf
python-pdfkit:
import pdfkit
pdfkit.from_url('http://example.com', 'output.pdf')
Summary
wkhtmltopdf is a powerful, standalone tool for converting HTML to PDF, offering more advanced features and flexibility. It's suitable for complex PDF generation tasks and can be used independently of Python.
python-pdfkit is a Python wrapper for wkhtmltopdf, providing a simpler interface for Python developers. It's easier to integrate into Python projects but may have limitations compared to direct wkhtmltopdf usage.
Choose wkhtmltopdf for more control and advanced features, or python-pdfkit for easier Python integration and simpler use cases.
The awesome document factory
Pros of WeasyPrint
- Pure Python implementation, no external dependencies required
- Supports CSS3 and HTML5 features for more advanced layouts
- Faster rendering for complex documents with many pages
Cons of WeasyPrint
- Less widespread adoption compared to wkhtmltopdf (used by python-pdfkit)
- May have compatibility issues with some older web technologies
Code Comparison
WeasyPrint:
from weasyprint import HTML
HTML('https://example.com').write_pdf('example.pdf')
python-pdfkit:
import pdfkit
pdfkit.from_url('https://example.com', 'example.pdf')
Both libraries offer simple one-line solutions for converting web pages to PDF. WeasyPrint uses a more Pythonic approach with its HTML class, while python-pdfkit relies on the underlying wkhtmltopdf tool.
WeasyPrint provides more flexibility for customizing the PDF output directly in Python, whereas python-pdfkit often requires passing options to the wkhtmltopdf command-line tool.
Overall, WeasyPrint is better suited for projects requiring advanced CSS support and pure Python implementations, while python-pdfkit may be preferred for simpler use cases or when compatibility with wkhtmltopdf is necessary.
Laravel Snappy PDF
Pros of laravel-snappy
- Seamless integration with Laravel framework, providing a more cohesive development experience
- Built-in support for Laravel's configuration system and service container
- Offers additional features like custom paper sizes and orientations
Cons of laravel-snappy
- Limited to Laravel projects, reducing flexibility for non-Laravel PHP applications
- Requires wkhtmltopdf to be installed on the server, which may pose deployment challenges
- Less extensive documentation compared to python-pdfkit
Code Comparison
laravel-snappy:
use Barryvdh\Snappy\Facades\SnappyPdf;
$pdf = SnappyPdf::loadView('pdf.invoice', $data);
return $pdf->download('invoice.pdf');
python-pdfkit:
import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')
Both libraries provide convenient methods for generating PDFs, but laravel-snappy is more tightly integrated with Laravel's ecosystem, while python-pdfkit offers a simpler, more language-agnostic approach. The choice between them largely depends on the project's framework and language requirements.
PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. Wrapper for wkhtmltopdf/wkhtmltoimage
Pros of snappy
- Multi-format support: Snappy can generate PDFs, images, and other formats, while python-pdfkit is primarily focused on PDF generation
- PHP-based: Ideal for PHP developers and projects, offering seamless integration with PHP applications
- Actively maintained: More recent updates and contributions compared to python-pdfkit
Cons of snappy
- Language limitation: Only available for PHP, whereas python-pdfkit is Python-based, limiting its use in non-PHP environments
- Learning curve: May require more setup and configuration compared to the simpler python-pdfkit
Code comparison
python-pdfkit:
import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')
snappy:
use Knp\Snappy\Pdf;
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
$snappy->generateFromHtml('<h1>Bill</h1><p>You owe me money, dude.</p>', '/tmp/bill-123.pdf');
$snappy->generateFromUrl('http://www.github.com', '/tmp/github.pdf');
Both libraries offer similar functionality for generating PDFs from various sources, but with syntax and usage patterns specific to their respective programming languages.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Python-PDFKit: HTML to PDF wrapper
.. image:: https://github.com/JazzCore/python-pdfkit/actions/workflows/main.yaml/badge.svg?branch=master :target: https://github.com/JazzCore/python-pdfkit/actions/workflows/main.yaml
.. image:: https://badge.fury.io/py/pdfkit.svg :target: http://badge.fury.io/py/pdfkit
Python 3 wrapper for wkhtmltopdf utility to convert HTML to PDF using Webkit.
This is adapted version of ruby PDFKit <https://github.com/pdfkit/pdfkit>
_ library, so big thanks to them!
Deprecation Warning
This library has been deprecated to match the wkhtmltopdf project status <https://wkhtmltopdf.org/status.html>
_.
Installation
- Install python-pdfkit:
.. code-block:: bash
$ pip install pdfkit
2. Install wkhtmltopdf:
- Debian/Ubuntu:
.. code-block:: bash
$ sudo apt-get install wkhtmltopdf
- macOS:
.. code-block:: bash
$ brew install homebrew/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 <http://wkhtmltopdf.org/>
_ site or you can use this script <https://github.com/JazzCore/python-pdfkit/blob/master/ci/before-script.sh>
_ (written for CI servers with Ubuntu 18.04 Bionic, but it could work on other Ubuntu/Debian versions).
- Windows and other options: check wkhtmltopdf
homepage <http://wkhtmltopdf.org/>
_ for binary installers
Usage
For simple tasks:
.. code-block:: python
import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')
You can pass a list with multiple URLs or files:
.. code-block:: python
pdfkit.from_url(['google.com', 'yandex.ru', 'engadget.com'], 'out.pdf')
pdfkit.from_file(['file1.html', 'file2.html'], 'out.pdf')
Also you can pass an opened file:
.. code-block:: python
with open('file.html') as f:
pdfkit.from_file(f, 'out.pdf')
If you wish to further process generated PDF, you can read it to a variable:
.. code-block:: python
# Without output_path, PDF is returned for assigning to a variable
pdf = pdfkit.from_url('http://google.com')
You can specify all wkhtmltopdf options <http://wkhtmltopdf.org/usage/wkhtmltopdf.txt>
_. 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).
.. code-block:: python
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-empty-value', '""')
('cookie-name1', 'cookie-value1'),
('cookie-name2', 'cookie-value2'),
],
'no-outline': None
}
pdfkit.from_url('http://google.com', 'out.pdf', options=options)
By default, PDFKit will run wkhtmltopdf
with quiet
option turned on, since in most cases output is not needed and can cause excessive memory usage and corrupted results. If need to get wkhtmltopdf
output you should pass verbose=True
to API calls:
.. code-block:: python
pdfkit.from_url('google.com', 'out.pdf', verbose=True)
Due to wkhtmltopdf command syntax, TOC and Cover options must be specified separately. If you need cover before TOC, use cover_first
option:
.. code-block:: python
toc = {
'xsl-style-sheet': 'toc.xsl'
}
cover = 'cover.html'
pdfkit.from_file('file.html', options=options, toc=toc, cover=cover)
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 <http://code.google.com/p/wkhtmltopdf/issues/detail?id=144>
_ in wkhtmltopdf. You should try --user-style-sheet option first.
.. code-block:: python
# Single CSS file
css = 'example.css'
pdfkit.from_file('file.html', options=options, css=css)
# Multiple CSS files
css = ['example.css', 'example2.css']
pdfkit.from_file('file.html', options=options, css=css)
You can also pass any options through meta tags in your HTML:
.. code-block:: python
body = """
<html>
<head>
<meta name="pdfkit-page-size" content="Legal"/>
<meta name="pdfkit-orientation" content="Landscape"/>
</head>
Hello World!
</html>
"""
pdfkit.from_string(body, 'out.pdf') #with --page-size=Legal and --orientation=Landscape
Configuration
Each API call takes an optional configuration parameter. This should be an instance of pdfkit.configuration()
API call. It takes the configuration options as initial parameters. The available options are:
wkhtmltopdf
- the location of thewkhtmltopdf
binary. By defaultpdfkit
will attempt to locate this usingwhich
(on UNIX type systems) orwhere
(on Windows).meta_tag_prefix
- the prefix forpdfkit
specific meta tags - by default this ispdfkit-
Example - for when wkhtmltopdf
is not on $PATH
:
.. code-block:: python
config = pdfkit.configuration(wkhtmltopdf='/opt/bin/wkhtmltopdf')
pdfkit.from_string(html_string, output_file, configuration=config)
Also you can use configuration()
call to check if wkhtmltopdf is present in $PATH
:
.. code-block:: python
try:
config = pdfkit.configuration()
pdfkit.from_string(html_string, output_file)
except OSError:
#not present in PATH
Troubleshooting
Debugging issues with PDF generation ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If you struggling to generate correct PDF firstly you should check wkhtmltopdf
output for some clues, you can get it by passing verbose=True
to API calls:
.. code-block:: python
pdfkit.from_url('http://google.com', 'out.pdf', verbose=True)
If you are getting strange results in PDF or some option looks like its ignored you should try to run wkhtmltopdf
directly to see if it produces the same result. You can get CLI command by creating pdfkit.PDFKit
class directly and then calling its command()
method:
.. code-block:: python
import pdfkit
r = pdfkit.PDFKit('html', 'string', verbose=True)
print(' '.join(r.command()))
# try running wkhtmltopdf to create PDF
output = r.to_pdf()
Common errors: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
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)
Top Related Projects
Convert HTML to PDF using Webkit (QtWebKit)
The awesome document factory
Laravel Snappy PDF
PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. Wrapper for wkhtmltopdf/wkhtmltoimage
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot