1

尝试使用 Flask 应用程序的 pdfkit 创建 .pdf 文件时出现错误。该应用程序确实可以在本地计算机上运行。当我尝试在 Digitalocean 的 Ubuntu 18.04 droplet 上运行代码时,问题开始出现(Nginx 用作 Web 服务器,Gunicorn(由主管协助)运行 wsgi)。这就是我在浏览器中遇到的错误(500):

服务器遇到内部错误,无法完成您的请求。服务器过载或应用程序出错。

这是 Gunicorn 错误日志中的错误:

[2019-07-27 14:44:56,969] ERROR in app: Exception on /store/resins/daylight/3 [POST]
Traceback (most recent call last):
  File "/home/slava/env/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/slava/env/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/slava/env/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/slava/env/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/home/slava/env/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/slava/env/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/slava/ag3d/ag3d/routes.py", line 184, in resin_store
    pdfkit.from_string(rendered, pdf_name, options = options)
  File "/home/slava/env/lib/python3.6/site-packages/pdfkit/api.py", line 72, in from_string
    return r.to_pdf(output_path)
  File "/home/slava/env/lib/python3.6/site-packages/pdfkit/pdfkit.py", line 159, in to_pdf
    raise IOError("wkhtmltopdf exited with non-zero code {0}. error:\n{1}".format(exit_code, stderr))
OSError: wkhtmltopdf exited with non-zero code 1. error:
qt.qpa.screen: QXcbConnection: Could not connect to display 
Could not connect to any X display.

这是应用程序使用 pdfkit 的方式:

options = {
  'page-size': 'A4',
  'margin-top': '0.75in',
  'margin-right': '0.75in',
  'margin-bottom': '0.75in',
  'margin-left': '0.75in',
}
rendered = render_template('order_doc.html', pdf_resin = pdf_resin)
pdfkit.from_string(rendered, pdf_name, options = options)
4

1 回答 1

0

PDFKit 包使用wkhtmltopdf,而后者又需要 X 服务器来运行。在 Debian 领域,这通常需要xvfb-run包装器。

headless_pdfkit包试图使jakewins提出的修补程序更易于使用。

您可以headless_pdfkit通过运行安装:

pip install headless-pdfkit

从字符串保存一个简单的 PDF。:

from headless_pdfkit import generate_pdf

ret = generate_pdf('<html></html>')
with open('output.pdf', 'wb') as w:
    w.write(ret)

options = {
    'auto_servernum': ''
}

ret = generate_pdf('<html></html>', options=options)
with open('output.pdf', 'wb') as w:
    w.write(ret)
于 2019-07-28T20:18:43.970 回答