在 Python 中获取 Weasyprint 的基本 URI

use*_*027 5 css python flask weasyprint

我正在使用 Python 的 Weasyprint 库试图将 html 文件打印为 pdf。我正在尝试将图像嵌入到我的页面背景中。这是代码:

HTML(string='''
    <h1>The title</h1>
    <p>Content goes here
''', base_url=os.path.dirname(os.path.realpath(__file__))).write_pdf("hello.pdf",  stylesheets=[CSS(string='body{background-image: url("example_image.png")}')])
Run Code Online (Sandbox Code Playgroud)

我得到这个代码的输出如下:

Ignored `background-image: url("example_image.png")` at 1:6, Relative URI reference without a base URI: 'example_image.png'.
blah@blah:~/Dropbox/Terraverde/annual_reports$ python3 test_excel.py
Run Code Online (Sandbox Code Playgroud)

我试图在 Stackoverflow 中搜索此问题的解决方案,并阅读了文档,但我能找到的最接近答案的是以下关于 Django 的相同问题的帖子:Django WeasyPrint CSS 集成警告:相对 URI 引用没有基本 URI:<link href="/static/css/bootstrap.min.css"> 在无行

我还尝试在我的代码中使用 document.baseURI:

base_url=os.path.dirname(os.path.realpath(__file__))).write_pdf("hello.pdf",  stylesheets=[CSS(string='body{background-image: url(document.baseURI + "example_image.png")}')])
Run Code Online (Sandbox Code Playgroud)

但这仍然产生了一个错误:

Parse error at 1:24, unexpected BAD_URI token in property value
Run Code Online (Sandbox Code Playgroud)

关于如何处理问题的任何建议,或者request.build_absolute_uri()对于常规 Python 或 Flask 的类似于 Django 的命令?

hen*_*ski 6

我有同样的错误,我有这个标签,在 OSX 上,在我用 pystache 渲染的模板中:

<img src="/Users/my_username/my_project/my_image.png" />
Run Code Online (Sandbox Code Playgroud)

所以我尝试了这个,它奏效了:

<img src="file:///Users/my_username/my_project/my_image.png" />
Run Code Online (Sandbox Code Playgroud)

只需在 /Users/... 路径之前添加 file:// 。(请注意,它是 3 个斜杠)。