Giter Club home page Giter Club logo

pychromepdf's Introduction

Pychromepdf PyPI version Travis build status Downloads

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

pychromepdf's People

Contributors

chibiegg avatar navin-mohan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

pychromepdf's Issues

win10 support?

Is it supported by win10? I use the path C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe , but it doesn't work.

pychromepdf throws error

Tried to run pychromepdf on Ubuntu with Chromium. When I run the code "Rendering HTML bytestring to PDF" from README.md,
I get the following messages:
[0414/031047.754278:WARNING:bluez_dbus_manager.cc(248)] Floss manager not present, cannot set Floss enable/disable.
[0414/031048.453954:ERROR:sandbox_linux.cc(377)] InitializeSandbox() called with multiple threads in process gpu-process.
[0414/031048.818869:INFO:headless_shell.cc(659)] Written to file test.pdf.
Successfully generated the pdf: test.pdf.
The generated pdf file is empty besides the header and footer line.

isinstance(html_byte_string,str) is too strict

Hi Navin,
I'm trying to use your library with Django template output. The rendered html is an instance of SafeText by default, but it can be converted to a unicode. We cannot further cast that unicode to str, because unicode characters (like ยฃ) are not supported by ASCII.

Since Chrome supports unicode text without any issues (as its default character encoding is utf-8), do you think it would be possible to accept an instance of unicode in addition to str in html_to_pdf?

ModuleNotFoundError: No module named 'pychromepdf'

I installed the module in Python3:

pip3 install pychromepdf

And then ran a test code in the README.md but got the module not found error:

Traceback (most recent call last):
  File "testPDF.py", line 1, in <module>
    from pychromepdf import ChromePDF
ModuleNotFoundError: No module named 'pychromepdf'

I am running this on Mac. Any idea? Thanks!

Quieter terminal output ๐Ÿ”•

Heya ๐Ÿ‘‹

subprocess.run(print_to_pdf_command,shell=isNotWindows,check=True)

Would you consider piping this output into the ether? ๐Ÿ‘€

subprocess.run(print_to_pdf_command,shell=isNotWindows,check=True,stderr=subprocess.PIPE)

This suppresses lots of 'noise' hitting the terminal when printing to PDF in Python.

It turns this:

[0703/141059.002551:ERROR:xattr.cc(63)] setxattr org.chromium.crashpad.database.initialized on file /var/folders/1v/kv1jvjdj24d2pyg35prp91ch0000gn/T/: Operation not permitted (1)
[0703/141059.003485:ERROR:file_io.cc(91)] ReadExactly: expected 8, observed 0
[0703/141059.004399:ERROR:xattr.cc(63)] setxattr org.chromium.crashpad.database.initialized on file /var/folders/1v/kv1jvjdj24d2pyg35prp91ch0000gn/T/: Operation not permitted (1)
[0703/141059.053767:WARNING:headless_browser_main_parts.cc(106)] Cannot create Pref Service with no user data dir.
[0703/141059.308297:INFO:headless_shell.cc(648)] Written to file Letter.pdf.

Into... Nothing ๐Ÿ˜Œ and still returns True/False depending on the result.

This is probably too simple a change & could probably have a complex "debug" flag built to pick between output & no output but I think it'd be ideal for the use cases I've run into in the past 6 months with pychromepdf.

I'm running into some permission errors when pushing a small new branch ๐Ÿค” so I've come via Issues instead ๐Ÿ˜‡

Add print options

Right now the options are part of the ChromePDF._chrome_options field.
Probably it should:

  • Add --print-to-pdf-no-header by default
  • Add the possibility of pass in new params

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.