用Python和wkhtmltopdf将HTML转换为PDF

2 投票
1 回答
5051 浏览
提问于 2025-04-17 17:46

我刚刚发现了一个叫做 wkhtmltopdf 的工具,它可以把HTML转换成PDF,使用的是webkit技术。 我在我的开发机器上试过,感觉简单易用,效果也很好。

这个工具怎么最好地和基于django的网站结合起来呢?

我找到了 python绑定,但是这些内容假设你对安装东西有一定的了解,而我对此并不太懂。例如:

you need libwkhtmltox.* somewhere in your LD path (/usr/local/lib)
you need the directory src/include/wkhtmltox from wkhtmltopdf
    somewhere on your include path (/usr/local/include)
  • 安装了这些python绑定后,我该怎么使用它们?我可以调用哪些功能?

  • 生成的PDF必须保存到硬盘上吗,还是可以通过某种方式直接从视图中输出?

举个例子:

response['Content-Disposition'] = 'attachment; filename='+letter_name
response['Content-Type'] = 'Content-type: application/octet-stream'
response['Content-Length'] = bytes
return response

1 个回答

4

我推荐你使用 django-wkhtmltopdf 来实现这个功能。它们的 使用文档 提供了一些示例,教你如何进行集成:

from django.conf.urls.defaults import *
from wkhtmltopdf.views import PDFTemplateView


urlpatterns = patterns('',
    # ...
    url(r'^pdf/$', PDFTemplateView.as_view(template_name='my_template.html',
                                           filename='my_pdf.pdf'), name='pdf'),
    # ...
)

撰写回答