【问题标题】:Wkhtmltopdf - How can I use a relative path?Wkhtmltopdf - 如何使用相对路径?
【发布时间】: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


    【解决方案1】:

    我建议在 Django 中使用 Wkhtmltopdf 以及 django-wkhtmltopdf 之类的东西,它将静态和媒体路径转换为 ​​PDF 所需的绝对路径。

    【讨论】:

    • 我想我正在使用 django-wkhtmltopdf。还是不行。
    • 您在使用 PDFTemplateView 吗?您的 STATIC_ROOT 设置是否在本地开发中? django-wkhtmltopdf.readthedocs.io/en/latest/…
    • 是的,我正在尝试遵循答案,但还有另一个错误。我编辑了这个问题。请检查一下好吗?
    猜你喜欢
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    相关资源
    最近更新 更多