pythonweasyprint OSError 路径错误

python weasyprint OSError bad path

我在尝试使用以下代码从 weasyprint 创建 pdf 时 运行 遇到的问题

from weasyprint import HTML
string_html = create_string_html()  # over simplified for question. It is created from a jinja template

HTML(string_html).write_pdf('example.pdf')

我收到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\...\site-packages\weasyprint\__init__.py", line 112, in __init__
    with result as (source_type, source, base_url, protocol_encoding):
  File "C:\...\Programs\Python\Python38\lib\contextlib.py", line 113, in __enter__
    return next(self.gen)
  File "C:\...\site-packages\weasyprint\__init__.py", line 396, in _select_source
    with result as result:
  File "C:\...\Python\Python38\lib\contextlib.py", line 113, in __enter__
    return next(self.gen)
  File "C:\...\weasyprint\__init__.py", line 402, in _select_source
    base_url = path2url(filename)
  File "C:\...\lib\site-packages\weasyprint\urls.py", line 98, in path2url
    path = pathname2url(path)
  File "C:\...\nturl2path.py", line 65, in pathname2url
    raise OSError(error)
OSError: Bad path: C:\...\<!DOCTYPE html>

此问题是 weasyprintHTML 函数的第一个参数正在寻找文件位置。为了传递一个字符串,使该字符串成为一个命名变量,如下所示:

HTML(string=string_html).write_pdf('example.pdf')

可在此处找到更多信息:Instantiating HTML and CSS objects

如 weasyprint 文档中所写:

from weasyprint import HTML

HTML('../foo.html')  # Same as …
HTML(filename='../foo.html')

所以你不能通过这种方式传递一个字符串,你必须明确声明你要给他一个字符串,注意CSS对象也是一样的。

from weasyprint import HTML

HTML(string='''
    <h1>The title</h1>
    <p>Content goes here
''')

CSS(string='@page { size: A3; margin: 1cm }') # Passing strings instead paths

希望对您有所帮助。
和乐.