【问题标题】:Weasyprint cant load images when rendering html string渲染html字符串时Weasyprint无法加载图像
【发布时间】:2020-07-25 23:51:21
【问题描述】:

我正在使用 python 开发 weasyprint 库,场景是我编写了一个简单的函数,它首先使用动态数据和徽标将 html 模板呈现为 html_string,然后我将该 html_string 转换为 pdf,但问题是当我转换 html_string到pdf它不显示图像(徽标),我经历了不同的解决方案,他们通过request.build_absolute_uri()解决了这个问题,但我没有请求参数,因为我的函数不是django视图,任何人都可以指导我如何渲染带有徽标的 html_template

def generatepdf(data):
    html = render_to_string('template.html', {"test": data})
    filename = data['version'] + ".pdf"
    try:
        # pdfkit.from_string(html.content.decode('utf-8'), filename, options=options)
        HTML(string=html).write_pdf(filename)
        return filename
    except Exception as e:
        print(e.__str__())
        return False

【问题讨论】:

  • 如果解决方案可以是build_absolute_uri,那么也许可以在您的 html 中手动创建绝对链接。或绝对 uri 从 file:// 开始
  • 顺便说一句:你如何运行这个函数?如果您在视图中运行它,那么您可以将其定义为def generatepdf(data, request): 并使用request 运行
  • 顺便说一句:您似乎不必运行request.build_absolute_uri(),但您可以手动添加此网址HTML(string=html_string, base_url="your_absolute_uri")。您只需要知道使用什么值作为绝对路径。
  • 你能指导我什么是我的绝对路径我的目录如下 project/static/logo/file 静态目录也注册了
  • 磁盘上的正常绝对路径在 Windows 上以 C:/ 开头,在 Windows/Linux/Mac 上以 / 开头 - 在 HTML 中它可能需要前缀 file:// - 就像在 Linux 上的 file:///home/user/documents/project/static/logo/file。当它必须是页面上元素的绝对路径时,它可能是http://your_domain.com/static/logo/file。但我不知道它在 PDF 中是如何工作的。

标签: python html django templates weasyprint


【解决方案1】:

使用 cmets 中提到的 base_url。 我个人将我的图像与我的 python 文件放在同一个文件夹中。只需将文件夹的绝对路径添加为 base_url 参数即可。

在python文件中:

html = HTML(string=html_string, base_url="/home/whatever/pdf_generator")

在html_string中(图片的绝对路径:/home/whatever/pdf_generator/my_image.png):

<img src="my_image.png" />

【讨论】:

    猜你喜欢
    • 2017-08-09
    • 1970-01-01
    • 2021-12-22
    • 2021-06-06
    • 2011-03-05
    • 2014-08-29
    • 2021-01-30
    • 2021-02-12
    • 2019-03-21
    相关资源
    最近更新 更多