我想把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是否有使用静态根路径的方法?
如何成功地转换它?
编辑
我正试着跟踪这个用django创建PDF (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
发布于 2017-09-19 20:07:37
我建议在Django中使用Wkhtmltopdf,同时使用类似django-wkhtmltopdf的方法,将静态和媒体路径转换为PDF所需的绝对路径。
https://stackoverflow.com/questions/46308017
复制相似问题