如何使用XHTML2PDF在PDF文件中添加静态文件?
我正在尝试使用XHTML2PDF
在我的PDF文件中的文件夹中添加静态图像。
我的app.py
看起来像这样。
from xhtml2pdf import pisa
from pathlib import Path
output_filename = "output.pdf"
source_html = Path('template.html').read_text()
print(source_html)
result_file = open(output_filename, "w+b")
pisaStatus = pisa.CreatePDF(
source_html,
dest=result_file)
result_file.close()
我的template.html
看起来像这样。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Title of the document.</h1>
<img src="img/logo.png" />
</body>
</html>
我的logo.png位于img
沿app.py
的侧面。
app.py
img/
logo.png
template.html
当我运行时
python app.py
,确实会生成PDF文件,但是丢失了图像。这给了我以下错误。
Extract data form local file
Need a valid file name!
'<img src="img/logo.png"/>'
如何解决这个问题?
I am trying add a static image which is already there in my folder in my pdf file using xhtml2pdf
.
My app.py
looks like this.
from xhtml2pdf import pisa
from pathlib import Path
output_filename = "output.pdf"
source_html = Path('template.html').read_text()
print(source_html)
result_file = open(output_filename, "w+b")
pisaStatus = pisa.CreatePDF(
source_html,
dest=result_file)
result_file.close()
And my template.html
looks like this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Title of the document.</h1>
<img src="img/logo.png" />
</body>
</html>
My logo.png lies in the img
folder along the side of app.py
.
app.py
img/
logo.png
template.html
When I run
python app.py
This do generate the pdf file, however the image is missing. And it gives me the following error.
Extract data form local file
Need a valid file name!
'<img src="img/logo.png"/>'
How to resolve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它适用于 Alpine 3.12。 Alpine升级到3.16后,我遇到了同样的错误。我必须通过
chmod 444 img/logo.png
使 png 文件对每个人都可读。It worked on Alpine 3.12. After the Alpine has upgraded to 3.16, I experienced the same error. I have to make the png file readable to everyone by
chmod 444 img/logo.png
.