【问题标题】:WeasyPrint HTML to PDF not rendered Images in TEST VM Environment - DjangoWeasyPrint HTML to PDF 未在 TEST VM 环境中呈现图像 - Django
【发布时间】:2020-04-08 02:15:32
【问题描述】:

我正在使用 Django + WeasyPrint 生成 HTML 到 PDF。

在 HTML 模板中,我有大约 2 个 SVG 文件。在开发(本地)服务器中运行时,它会在将 HTML 转换为 PDF 时呈现 SVG 图像。而在 TEST Server(使用 NGINX 和 Docker Container 运行)中,它无法渲染 SVG 文件。在 WeasePrint 中,我在 base_url 中提到了我的 TEST URL (http//test.sampleproject.com:8000)。我不知道为什么它在我的开发服务器中工作而在测试服务器中不起作用

我的代码。

html_string = render_to_string('sample.html', {'data': data})
result = HTML(string=html_string, base_url='http//test.sampleproject.com:8000').write_pdf(presentational_hints=True)
response = HttpResponse(result, content_type='application/pdf')
response['Content-Disposition'] = 'inline; filename={}'.format('sample.pdf')
return response

在我的模板文件中,我加载了大约 10 张图片。例如:“sample.html”模板文件:

  {% load staticfiles %}
  <img src="{% static 'svg/Logo1.svg' %}" alt="" />
  <img src="{% static 'svg/Logo2.svg' %}" alt="" />

请帮我在输出 PDF 中渲染 SVG 文件。

【问题讨论】:

标签: django python-3.x docker nginx weasyprint


【解决方案1】:

我过去曾使用 Django + Weasyprint 完成过一些工作,我唯一一次在渲染图像时遇到问题是因为 Weasyprint 以不同的方式访问图像。

我发现我必须为它添加一个静态端点来访问文件,因为它从外部向 Django 请求静态图像。以下是如何让您的静态资源能够被外部访问;

https://docs.djangoproject.com/en/3.0/howto/static-files/#s-serving-static-files-during-development

正如 FlipperPA 所提到的,确保您的服务器上安装了所有操作系统级别的库;

https://weasyprint.readthedocs.io/en/latest/install.html

希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 2020-09-03
    • 2016-01-01
    • 2020-01-05
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 2019-07-27
    相关资源
    最近更新 更多