【发布时间】:2017-09-19 19:03:45
【问题描述】:
我想将 Django 模板转换为 pdf 文件。模板中的图像:
<img src="{% static "img/person.png" }%" />
改为
<img src="/static/img/person.png" />
它在浏览器中运行良好。
但是当我尝试使用 Wkhtmltopdf 模块将此 html 文件转换为 pdf 文件时,出现错误:
$ wkhtmltopdf --javascript-delay 5000 report.html report.pdf
Warning: Failed to load file:///static/img/person.png (ignore)
似乎 Wkhtmltopdf 模块只需要绝对路径。
如果我将 src 设置为绝对路径,例如:
<img src="/home/bingbong/django/project/apps/static/img/person.png" />
效果很好,但我知道这不是一个好方法。
有什么方法可以在 Wkhtmltopdf 中使用静态根路径?
如何才能成功转换?
编辑
我正在尝试关注这个Creating PDFs with django (wkhtmltopdf)
但是,有一个严重的
Error: Failed loading page http://false (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: HostNotFoundError
subprocess.CalledProcessError: Command '['/usr/bin/wkhtmltopdf', '--encoding', 'utf8', '--javascript-delay', '1000', '--quiet', 'False', '/tmp/wkhtmltopdf3atfj280.html', '-']' returned non-zero exit status 1
我不知道为什么有http://false。
这是我的 urls.py
app_name = 'apps'
urlpatterns =[
url(r'^pdf/$', views.MyPDFView.as_view()),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
这是我的 settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
WKHTMLTOPDF_CMD = '/usr/bin/wkhtmltopdf'
WKTHMLTOPDF_CMD_OPTIONS ={
'quiet': False,
}
这是 MyPDFView 类
class MyPDFView(View):
template='apps/Report.html' # the template
def get(self, request):
response = PDFTemplateResponse(
request=request,
template=self.template,
filename="apps/Report.pdf",
show_content_in_browser=False,
cmd_options={
'javascript-delay':1000,
'quiet':False,
},
)
return response
【问题讨论】:
标签: python django wkhtmltopdf