简体   繁体   English

使用Python将HTML / CSS / Javascript文件转换为PDF?

[英]Convert a HTML/CSS/Javascript file to PDF using Python?

I need to convert a HTML+CSS+Javascript file to PDF from a Django View and therefor using Python. 我需要使用Python将HTML + CSS + Javascript文件从Django View转换为PDF。

I could use xhtml2pdf/PISA but it only supports HTML & CSS, not Javascript, which is required. 我可以使用xhtml2pdf / PISA,但它只支持HTML和CSS,而不是Javascript,这是必需的。

Another option would be py-wkhtmltox, but it's getting pretty old and I haven't been able to get it to work yet, I just get "ImportError: libwkhtmltox.so.0: cannot open shared object file: No such file or directory", not sure where to get that file other then just to out of the blue rename libwkhtmltox.so to libwkhtmltox.so.0, but then I just get: 另一种选择是py-wkhtmltox,但它已经很老了,我还没能让它工作,我只是得到“ImportError:libwkhtmltox.so.0:无法打开共享对象文件:没有这样的文件或目录“,不知道从哪里获取该文件只是为了蓝色重命名libwkhtmltox.so到libwkhtmltox.so.0,但后来我得到:

Traceback (most recent call last):
  File "pdf_test1.py", line 5, in <module>
    pdf.set_object_setting('path', 'http://www.google.com')
  File "wkhtmltox.pyx", line 118, in wkhtmltox.Pdf.__getattr__ (wkhtmltox.c:1228)
AttributeError: 'wkhtmltox._Pdf' object has no attribute 'set_object_setting'

Yet another option would be to use webkit ( http://bharatikunal.wordpress.com/2010/01/31/converting-html-to-pdf-with-python-and-qt/ ) but I can't execute "sys.exit(app.exec_())" from a Django view. 另一个选择是使用webkit( http://bharatikunal.wordpress.com/2010/01/31/converting-html-to-pdf-with-python-and-qt/ )但我不能执行“sys .exit(app.exec_())“来自Django视图。

The only thing I can think of right now is to create a seperate webkit python script and os.system it from the django view, making "sys.exit(app.exec_())" possible and therefor the resultin PDF. 我现在唯一能想到的就是从django视图创建一个单独的webkit python脚本和os.system,使“sys.exit(app.exec_())”成为可能,从而得到PDF的结果。 But I'm open to other suggestions, seams a bit strange to use os.system from a django view. 但我对其他建议持开放态度,从django视图中使用os.system有点奇怪。

Any ideas? 有任何想法吗?

I suggest using wkhtmltopdf . 我建议使用wkhtmltopdf It's available as a static binary for linux, so you shouldn't run into any shared object problems. 它可以作为linux的静态二进制文件使用,因此您不应该遇到任何共享对象问题。 wkhtmltopdf wraps webkit and supports javascript, and you can even tell it for how long to run any JS code before the rendering takes place. wkhtmltopdf包装webkit并支持javascript,你甚至可以告诉它在渲染发生之前运行任何JS代码的时间。 I've used it successfully to make PDFs of pages that had some complicated chart generating code on them. 我已经成功地使用它制作了一些页面的PDF,这些页面上有一些复杂的图表生成代码。 Just launch it using subprocess.call() . 只需使用subprocess.call()启动它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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