Skip to main content

Pychromepdf PyPI version Travis build status

Pychromepdf is a Python package that lets you easily create PDFs by rendering HTML content using Chrome or Chromium as backend. It works without any external dependecies except a working installation of Chrome or Chromium that supports headless mode.

Installation

pip install pychromepdf

Usage

Rendering HTML bytestring to PDF

from pychromepdf import ChromePDF

# change to your chrome executable path
PATH_TO_CHROME_EXE = '/usr/bin/google-chrome-stable'
# if you're on MacOS
# PATH_TO_CHROME_EXE = '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome'

if __name__ == '__main__':
    # initialize chromepdf object
    cpdf = ChromePDF(PATH_TO_CHROME_EXE)

    # the html that need to be rendered into pdf
    html_bytestring = '''
    <!doctype html>
    <html>
        <head>
            <style>
            @media print {
                @page { margin: 0; }
                body { margin: 1.6cm; }
            }
            </style>
        </head>
        <body>
            <h1>Hello, World</h1>
            <h5> Generated using headless chrome </h5>
        </body>
    </html>
    '''

    # create a file and write the pdf to it
    with open('test.pdf','w') as output_file:
        if cpdf.html_to_pdf(html_bytestring,output_file):
            print("Successfully generated the pdf: {}".format(output_file.name))
        else:
            print("Error generating pdf")

Rendering a flask template into PDF

from flask import Flask, render_template, send_file
import tempfile
from pychromepdf import ChromePDF

app = Flask(__name__)

# change to your chrome executable path
PATH_TO_CHROME_EXE = '/usr/bin/google-chrome-stable'
# if you're on MacOS
# PATH_TO_CHROME_EXE = '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome'

# initialize a chromepdf object
cpdf = ChromePDF(PATH_TO_CHROME_EXE)

# home route
@app.route('/')
def index():
    return render_template('index.html',username="John")

# custom pdf route
@app.route('/getpdf',defaults={'username': 'John'})
@app.route('/getpdf/<username>')
def getpdf(username):

    # get the rendered html as string using the template
    rendered_html = render_template('index.html',username=username)

    # create a temporary output file which will be deleted when closed
    with tempfile.NamedTemporaryFile(suffix='.pdf') as output_file:

        # create a pdf from the rendered html and write it to output_file
        if cpdf.html_to_pdf(rendered_html,output_file):
            print("PDF generated successfully: {0}".format(output_file.name))

            try:
                # send the file to user
                return send_file(output_file.name,attachment_filename='awesome.pdf')
            except Exception as e:
                return str(e)
        else:
            print("Error creating PDF")

    return "Error"
                

if __name__ == '__main__':
    app.run(debug=True)

Template

{# templates/index.html #}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        @media print {
            @page { margin: 0; }
            body { margin: 1.6cm; }
        }
    </style>    
</head>
<body>
    <h1>Hello {{ username }}!</h1>
    <h4>Generated using ChromePDF</h4>
</body>
</html>

Contributors

License

MIT License

Metadata

Release files for pychromepdf 1.1

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

Source distribution (sdist)

Source distribution for pychromepdf 1.1
File Size Uploaded Provenance Actions
pychromepdf-1.1.tar.gz 3.6 kB Without provenance Details for pychromepdf-1.1.tar.gz

Release files / pychromepdf-1.1.tar.gz

Download URL pychromepdf-1.1.tar.gz
Size 3.6 kB
Tags Source
SHA-256 checksum
How to use checksums
43fe030b6d19778f07ea9b204b8d68e14ac5fa6fef222e8445e098d97b6826b2
BLAKE2b-256 checksum
How to use checksums
57f475d2ef3b4a93b253924f56a3c0617768a1dbdc342ee552da596778f5bb8c
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/47.1.1 requests-toolbelt/0.9.1 tqdm/4.46.1 CPython/3.6.7

Security for pychromepdf 1.1

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.

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