简体   繁体   中英

How to generate PDF file from an HTML file using Reportlab and Pisa in Python?

Have the following code setup as follows to generate a PDF document using Reportlab and Pisa in Python.

import cStringIO
import ho.pisa as pisa

def html_to_pdf(data, filename, open=False):
    pdf = pisa.CreatePDF(
        cStringIO.StringIO(data),
        file(filename, "wb"))

My HTML file contains standard HTML content.

It's fully qualified path along with .html extension is assigned to the output_file variable.

Call it like this:

with open(output_file, "r") as my_file:
        contents = my_file.read()

html_to_pdf(contents, dest_pdf_file, open=True)

Get this error:

No handlers could be found for logger "sx.pisa3"
Traceback (most recent call last):
  File "/home/devuser/myapp/app.py", line 8, in <module>
    from utils.fileutils import FileUtil
  File "/home/devuser/myapp/utils/fileutils.py", line 5, in <module>
    import ho.pisa as pisa
  File "/usr/local/lib/python2.7/dist-packages/pisa-3.0.33-py2.7.egg/ho/pisa/__init__.py", line 26, in <module>
    from sx.pisa3.pisa import *
  File "/usr/local/lib/python2.7/dist-packages/pisa-3.0.33-py2.7.egg/sx/pisa3/__init__.py", line 41, in <module>
    from pisa import *
  File "/usr/local/lib/python2.7/dist-packages/pisa-3.0.33-py2.7.egg/sx/pisa3/pisa.py", line 32, in <module>
    from pisa_document import *
  File "/usr/local/lib/python2.7/dist-packages/pisa-3.0.33-py2.7.egg/sx/pisa3/pisa_document.py", line 22, in <module>
    from pisa_context import pisaContext
  File "/usr/local/lib/python2.7/dist-packages/pisa-3.0.33-py2.7.egg/sx/pisa3/pisa_context.py", line 21, in <module>
    from pisa_util import *
  File "/usr/local/lib/python2.7/dist-packages/pisa-3.0.33-py2.7.egg/sx/pisa3/pisa_util.py", line 55, in <module>
    raise ImportError("Reportlab Version 2.1+ is needed!")
ImportError: Reportlab Version 2.1+ is needed!

This is a "partial list" of what pip freeze yields.

Pillow==2.3.0
PyPDF2==1.25.1
html5lib==0.999
oneconf==0.3.7.14.04.1
pdfkit==0.5.0
pisa==3.0.33
reportlab==3.0

Seems like a broken installation issue...

Does anyone know how to fix this or any alternative methods (approaches and / or different libraries) used to generate HTML files into PDFs?

Got it working... Uninstalled and reinstalled pisa and it worked! :)

sudo easy_install pisa

My code:

import cStringIO
import ho.pisa as pisa

class FileUtil:
    @staticmethod
    def html_to_pdf(html, output_file):
        pdfFile = file(output_file, "wb")
        pdf = pisa.CreatePDF(
            cStringIO.StringIO(html.encode("ISO-8859-1")), pdfFile)
        pdfFile.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM