在Python中获取Weasyprint的基本URI
我正在使用Python的Weasyprint库,试图将html文件打印成pdf。我试图在我的页面背景中嵌入图像。代码如下:在Python中获取Weasyprint的基本URI,python,css,flask,weasyprint,Python,Css,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
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")}')])
我曾尝试搜索Stackoverflow以寻找此问题的解决方案,并阅读了文档,但我能找到的最接近答案是以下关于Django的相同问题的帖子:
我还尝试在代码中使用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")}')])
但这仍然产生了一个错误:
Parse error at 1:24, unexpected BAD_URI token in property value
对于如何处理问题,或者类似于Django的
request.build\u absolute\u uri()
的命令,您有什么建议吗 我的错误与我在OSX上用pystache呈现的模板中的标签相同:
<img src="/Users/my_username/my_project/my_image.png" />
因此,我尝试了这个方法,效果很好:
<img src="file:///Users/my_username/my_project/my_image.png" />
只需在/Users/…之前添加file://即可。。。路径(注意它是3个斜杠)。我发现
base\u url
必须作为参数提供给weasyprint.CSS
函数,而不是weasyprint.HTML
函数:
从weasyprint导入HTML、CSS
html_content=''标题内容放在这里''
base_url=os.path.dirname(os.path.realpath(_文件__))
css=css(string='body{background image:url(“example_image.png”)}',base_url=base_url)
HTML(string=HTML\u content)。编写pdf(“hello.pdf”,样式表=[css])
作为奖励,加载位于此脚本旁边的font
文件夹中的本地字体也是如此:
#用于调试
导入日志记录
logger=logging.getLogger('weasyprint')
logger.addHandler(logging.StreamHandler())
导入操作系统
从weasyprint导入HTML、CSS
从weasyprint.fonts导入FontConfiguration
html_content=''标题内容放在这里''
font\u config=FontConfiguration()
此文件\u DIR=os.path.dirname(os.path.abspath(\u文件\u))+os.sep
基本url='file://'+此文件目录
#从下载的字体
# https://fonts.google.com/specimen/Poppins?preview.text_type=custom&sidebar.open=true&selection.family=Poppins:wght@400;500;600;700
css=css(字符串=“”)
@字体{
字体系列:“Poppins”;
src:url('./font/Poppins-Regular.ttf')格式('truetype');
字体大小:400;
字体风格:普通;
}
@字体{
字体系列:“Poppins”;
src:url('./font/Poppins-Medium.ttf')格式('truetype');
字号:500;
字体风格:普通;
}
@字体{
字体系列:“Poppins”;
src:url('./font/Poppins-SemiBold.ttf')格式('truetype');
字号:600;
字体风格:普通;
}
@字体{
字体系列:“Poppins”;
src:url('../base/font/Poppins Bold.ttf')格式('truetype');
字号:700;
字体风格:普通;
}
'',font\u config=font\u config,base\u url=base\u url)
HTML(string=HTML\u content)。编写pdf(“hello.pdf”,样式表=[css])
<img src="file:///Users/my_username/my_project/my_image.png" />