win10 环境下使用 django-wkhtmltopdf 将 HTML 转换成 PDF

环境版本:

  • python 2.7.10
  • Django 1.8.5
  • django-wkhtmltopdf 3.1.0

使用步骤:

  1. 下载并安装相应的系统版本:wkhtmltopdf static binary
  2. 在项目中安装包:pip install django-wkhtmltopdf
  3. settings.py 中将 wkhtmltopdf 添加到 INSTALLED_APPS 中:
INSTALLED_APPS = (
    # ...
    'wkhtmltopdf',
    # ...
)

By default it will try to execute the wkhtmltopdf command from your PATH.
If you can't add wkhtmltopdf to your PATH, you can use the WKHTMLTOPDF_CMD setting:
WKHTMLTOPDF_CMD = '/path/to/my/wkhtmltopdf'
or alternatively as env variable:
export WKHTMLTOPDF_CMD=/path/to/my/wkhtmltopdf
在我机器上的设置为:WKHTMLTOPDF_CMD = 'C:/wkhtmltopdf/bin/wkhtmltopdf'

  1. settings.py 中设置 STATIC_ROOT = os.path.join(BASE_DIR, 'static'),不然会报错:'NoneType' object has no attribute 'endswith'
简单应用:

适合静态 HTML 模版
urls.py 中添加:

from wkhtmltopdf.views import PDFTemplateView

urlpatterns = [
    url(r'^simple_pdf/$', PDFTemplateView.as_view(template_name='simple_template.html', filename='simple_pdf.pdf'), name='simple_pdf'),
]

simple_template.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>hello PDF</h1>
</body>
</html>
高级应用:

适合动态 HTML 模版,需要自定义类并继承 PDFTemplateView

from wkhtmltopdf.views import PDFTemplateView

class MyPDFView(PDFTemplateView):
    filename = 'my_pdf.pdf'
    template_name = 'my_template.html'

    def get_context_data(self, **kwargs):
        context = super(MyPDF, self).get_context_data(**kwargs)
        # 添加模版中需要的内容
        context['name'] = 'hello PDF'
        return context

urls.py 中添加:

urlpatterns = [
    url(r'^senior_pdf/$', MyPDFView.as_view(), name='senior_pdf'),
]

my_template.html 内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>{{ name }}</h1>
</body>
</html>

推荐阅读更多精彩内容