WeasyPrint入门指南:从安装到PDF生成全解析
WeasyPrint The awesome document factory 项目地址: https://gitcode.com/gh_mirrors/we/WeasyPrint
WeasyPrint是一个强大的Python库,能够将HTML和CSS文档转换为高质量的PDF文件。本文将详细介绍WeasyPrint的安装方法、基本使用以及安全注意事项,帮助开发者快速上手这一工具。
系统要求与安装
基础依赖
WeasyPrint需要以下核心组件支持:
- Python ≥ 3.9.0
- Pango ≥ 1.44.0(用于文本布局和渲染)
- 其他关键Python库:pydyf、CFFI、tinyhtml5、tinycss2等
各平台安装指南
Linux系统
推荐优先使用发行版的包管理器安装:
# Debian/Ubuntu
sudo apt install weasyprint
# Fedora
sudo dnf install weasyprint
# Archlinux
sudo pacman -S python-weasyprint
如需最新版本,可通过pip安装:
python3 -m venv venv
source venv/bin/activate
pip install weasyprint
macOS系统
使用Homebrew安装最为简便:
brew install weasyprint
Windows系统
Windows用户有两种选择:
- 直接下载预编译的可执行文件
- 通过Python环境安装(需额外步骤):
- 安装Python 3.9+
- 通过MSYS2安装Pango
- 创建虚拟环境并安装WeasyPrint
python -m venv venv
venv\Scripts\activate.bat
pip install weasyprint
基本使用方式
命令行工具
WeasyPrint提供了便捷的命令行接口:
weasyprint input.html output.pdf
支持多种输入源:
- 本地HTML文件
- 网络URL
- 标准输入流
可通过-s
参数添加自定义样式:
weasyprint input.html output.pdf -s <(echo 'body { font-size: 12pt }')
Python API
在Python中使用WeasyPrint更加灵活:
from weasyprint import HTML
# 从URL生成PDF
HTML('https://example.com').write_pdf('output.pdf')
# 从字符串生成PDF
HTML(string='<h1>标题</h1><p>内容...</p>').write_pdf('output.pdf')
高级功能
- 自定义字体:
from weasyprint.text.fonts import FontConfiguration
font_config = FontConfiguration()
css = CSS(string='''
@font-face {
font-family: CustomFont;
src: url(/path/to/font.ttf);
}
body { font-family: CustomFont }
''', font_config=font_config)
HTML(...).write_pdf(..., stylesheets=[css], font_config=font_config)
- 分页控制:
document = HTML(...).render()
# 获取奇数页
document.copy(document.pages[::2]).write_pdf('odd_pages.pdf')
- 自定义资源加载:
def custom_fetcher(url):
if url.startswith('special:'):
return {'string': generate_content(url), 'mime_type': 'text/html'}
return default_url_fetcher(url)
HTML(..., url_fetcher=custom_fetcher).write_pdf(...)
安全注意事项
处理不可信HTML/CSS时需特别注意:
- 资源消耗:恶意文档可能导致长时间渲染或高内存占用
- 本地文件泄露:CSS中的
local()
函数可能访问系统字体 - 网络访问:文档可能包含对外部资源的请求
建议措施:
- 在受限用户权限下运行服务
- 使用容器隔离环境
- 限制最大处理时间和内存使用
- 禁用网络访问(通过自定义URL fetcher)
常见问题解决
-
缺少库文件:
- Windows:设置
WEASYPRINT_DLL_DIRECTORIES
环境变量指向库目录 - macOS:设置
DYLD_FALLBACK_LIBRARY_PATH
包含Homebrew库路径
- Windows:设置
-
字体显示问题:
- 确保系统安装了所需字体
- 使用
@font-face
明确指定字体 - 检查字体文件权限
-
性能优化:
- 对于批量处理,保持Python进程长期运行
- 复用FontConfiguration对象
- 预加载常用资源
通过本文介绍,您应该已经掌握了WeasyPrint的基本使用方法。无论是简单的文档转换还是复杂的PDF生成需求,WeasyPrint都能提供灵活的解决方案。
WeasyPrint The awesome document factory 项目地址: https://gitcode.com/gh_mirrors/we/WeasyPrint
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考