You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu18.04下WeasyPrint生成PDF加页脚图片时报PosixPath属性错误

解决WeasyPrint依赖报错及页脚图片路径问题

错误根源分析

你遇到的AttributeError: 'PosixPath' object has no attribute 'read_text',本质是**cairocffi版本与Python 3.6.7不兼容**。从cairocffi 2.1.0版本开始,官方不再支持Python 3.6,高版本的cairocffi使用了仅在Python 3.7+中完善的Path.read_text()方法,导致你的Python 3.6环境无法识别该方法。

另外,你的代码中页脚图片的URL格式也存在问题,后续依赖问题解决后可能会出现图片加载失败的情况,这里一起修正。

解决方案步骤

1. 降级兼容的cairocffi版本

卸载当前不兼容的cairocffi,安装支持Python 3.6的最高版本:

pip uninstall -y cairocffi
pip install cairocffi==2.0.0

2. 确保WeasyPrint版本兼容Python 3.6

WeasyPrint 53.0及以上版本要求Python 3.7+,所以需要安装52.x系列的兼容版本:

pip uninstall -y weasyprint
pip install weasyprint==52.5

3. 修正页脚图片的URL路径

你的代码中file://后面缺少了一个斜杠,Linux下本地文件的URL格式应为file:///(三个斜杠),否则WeasyPrint无法正确识别文件路径。修改CSS字符串部分:

css = CSS(string='@page { @bottom-center { width: 125%; margin-top: 10px; content: " "; background-image: url(file:///' + os.getcwd() + '/pdf/footer.png); background-repeat: no-repeat; background-position: right; background-size: 100%; } }')

或者用更稳妥的os.path.join拼接路径,避免手动拼接出错:

footer_path = os.path.join(os.getcwd(), 'pdf', 'footer.png')
css = CSS(string=f'@page {{ @bottom-center {{ width: 125%; margin-top: 10px; content: " "; background-image: url(file:///{footer_path}); background-repeat: no-repeat; background-position: right; background-size: 100%; }} }}')

验证运行

完成以上步骤后,重新执行你的Python脚本,应该可以正常生成带页脚图片的PDF文件了。

内容的提问来源于stack exchange,提问作者deleuterio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:56:34