【发布时间】: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