我正在使用姜戈。这是views.py 中的代码。
def download_as_pdf_view(request, doc_type, pk):
import pdfkit
file_name = 'invoice.pdf'
pdf_path = os.path.join(settings.BASE_DIR, 'static', 'pdf', file_name)
template = get_template("paypal/card_invoice_detail.html")
_html = template.render({})
pdfkit.from_string(_html, pdf_path)
return FileResponse(open(pdf_path, 'rb'), filename=file_name, content_type='application/pdf')
回溯如下。
[2022-09-05 00:56:35,785] ERROR [django.request.log_response:224] Internal Server Error: /paypal/download_pdf/card_invoice/MTE0Nm1vamlva29zaGkz/
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/project/app/paypal/views.py", line 473, in download_as_pdf_view
pdfkit.from_string(str(_html), pdf_path)
File "/usr/local/lib/python3.8/site-packages/pdfkit/api.py", line 75, in from_string
return r.to_pdf(output_path)
File "/usr/local/lib/python3.8/site-packages/pdfkit/pdfkit.py", line 201, in to_pdf
self.handle_error(exit_code, stderr)
File "/usr/local/lib/python3.8/site-packages/pdfkit/pdfkit.py", line 155, in handle_error
raise IOError('wkhtmltopdf reported an error:\n' + stderr)
OSError: wkhtmltopdf reported an error:
Exit with code 1 due to network error: ProtocolUnknownError
[2022-09-05 00:56:35,797] ERROR [django.server.log_message:161] "GET /paypal/download_pdf/card_invoice/MTE0Nm1vamlva29zaGkz/ HTTP/1.1" 500 107486
这是工作文件。
pdfkit.from_url('https://google.com', 'google.pdf')
However pdfkit.from_string
and pdfkit.from_file
返回“协议未知错误”
请帮我!
Update
我打了这个代码。
_html = '''<html><body><h1>Hello world</h1></body></html>'''
pdfkit.from_string(_html), pdf_path)
效果很好。我将上面的html保存为sample.html。然后运行这段代码
- 我添加了这个参数
options={"enable-local-file-access": ""}
_html = render_to_string('path/to/sample.html')
pdfkit.from_string(str(_html), pdf_path, options={"enable-local-file-access": ""})
效果很好!由于“ProtocolUnknownError”错误消失了options={"enable-local-file-access": ""}
.
因此,我将 HTML 文件路径更改为我真正想要使用的路径。
_html = render_to_string('path/to/invoice.html')
pdfkit.from_string(_html, pdf_path, options={"enable-local-file-access": ""})
return FileResponse(open(pdf_path, 'rb'), filename=file_name, content_type='application/pdf')
它没有完成转换 pdf。当我逐行运行代码时。
stdout, stderr = result.communicate(input=input)
不返回。
处理时间很长。