在python中将html字符串保存为PDF

时间:2014-12-16 15:39:05

标签: python wkhtmltopdf node-pdfkit

我有一个html字符串,我想在python中存储为PDF文件。我正在使用PDFkit来达到这个目的。以下是我为此目的而尝试的代码。在下面的代码中,我也尝试通过龙卷风服务器提供图像。

class MainHandler(RequestHandler):
    def get(self):
        self.write('hello!')

class ImageHandler(RequestHandler):    
    def get(self):
        d={}
        d["mov1"]=1
        d["mov2"]=10
        d["mov3"]=40
        d["mov4"]=3
        py.bar(range(len(d)),d.values(),align="center")
        py.xticks(range(len(d)),d.keys())
        io=StringIO()
        py.savefig(io,format='svg')
        self.set_header("Content-Type", "image/svg+xml")
        print io.getvalue()

        config = pdfkit.configuration(wkhtmltopdf='E:\\wkhtmltopdf\\bin')

        pdfkit.from_string(io.getvalue(),"E:\\hello.pdf",configuration=config) #Error here

        self.write(io.getvalue())


app = Application([
    url(r"/", MainHandler),
    url(r"/Image",ImageHandler)
    ])

if __name__=="__main__":
    app.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

我在E盘中安装了wkhtmltopdf。我得到了例外,

ERROR:tornado.application:Uncaught exception GET /Image (::1)
HTTPServerRequest(protocol='http', host='localhost:8888', method='GET', uri='/Image', version='HTTP/1.1', remote_ip='::1', headers={'Accept-Language': 'en-US,en;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch', 'Host': 'localhost:8888', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Connection': 'keep-alive', 'Cookie': '_ga=GA1.1.359367893.1418721747', 'If-None-Match': '"ee884f005691a9736e5e380cc68cd4c9679bf2a7"'})
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\tornado\web.py", line 1332, in _execute
    result = method(*self.path_args, **self.path_kwargs)
  File "E:\eclipse_workspace\Visualisation\module1\mod1.py", line 61, in get
    config = pdfkit.configuration(wkhtmltopdf='E:\\wkhtmltopdf\\bin')
  File "C:\Python27\lib\site-packages\pdfkit\api.py", line 79, in configuration
    return Configuration(**kwargs)
  File "C:\Python27\lib\site-packages\pdfkit\configuration.py", line 27, in __init__
    'https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf' % self.wkhtmltopdf)
IOError: No wkhtmltopdf executable found: "E:\wkhtmltopdf\bin"
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf
ERROR:tornado.access:500 GET /Image (::1) 246.00ms

虽然我愿意使用任何其他套餐。我也想知道我在做什么错误。

1 个答案:

答案 0 :(得分:0)

This链接说,鉴于上述错误,路径应设置为wkhtmltopdf二进制文件的位置。我以为我做了。但是当将配置更改为

时,它对我有用
config = pdfkit.configuration(wkhtmltopdf='E:\\wkhtmltopdf\\bin\\wkhtmltopdf.exe')