WeasyPrint作为一款功能强大的Python文档工厂,能够将HTML和CSS完美转换为高质量的PDF文件。无论您是开发者还是内容创作者,这个工具都能极大提升您的文档处理效率。本文将带您从零开始,全面掌握WeasyPrint的核心用法。
【免费下载链接】WeasyPrintThe awesome document factory项目地址: https://gitcode.com/gh_mirrors/we/WeasyPrint
为什么选择WeasyPrint?
在众多PDF生成工具中,WeasyPrint凭借其独特优势脱颖而出:
- 完美CSS支持:完整支持CSS3规范,包括flexbox、grid布局等现代特性
- 高质量输出:生成的PDF文件保持原始设计的精确性和美观度
- 跨平台兼容:支持Windows、macOS和Linux三大主流操作系统
- 开源免费:基于BSD许可证,可自由使用和修改
环境搭建与快速开始
安装步骤详解
对于不同操作系统,安装方式略有差异:
Linux用户(推荐)
sudo apt update sudo apt install weasyprintmacOS用户
brew install weasyprintWindows用户
pip install weasyprint验证安装成功
安装完成后,可以通过以下命令验证:
weasyprint --version核心功能操作演示
基础PDF生成
最简单的PDF生成只需要几行代码:
from weasyprint import HTML # 从HTML字符串生成PDF html_content = ''' <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; margin: 40px; } h1 { color: #2c3e50; border-bottom: 2px solid #3498db; } .content { line-height: 1.6; } </style> </head> <body> <h1>我的第一个PDF文档</h1> <div class="content"> <p>这是通过WeasyPrint生成的专业PDF文档。</p> <p>支持中文、表格、图片等丰富内容。</p> </div> </body> </html> ''' HTML(string=html_content).write_pdf('my_document.pdf')高级样式控制
WeasyPrint支持复杂的CSS布局,包括:
from weasyprint import HTML, CSS # 添加外部样式表 styles = CSS(string=''' @page { size: A4; margin: 2cm; } .header { text-align: center; font-size: 24px; margin-bottom: 20px; } .footer { position: fixed; bottom: 0; width: 100%; text-align: center; font-size: 10px; color: #666; } ''') HTML(string=html_content).write_pdf( 'styled_document.pdf', stylesheets=[styles] )自定义字体与国际化
处理多语言文档时,字体配置至关重要:
from weasyprint import HTML, CSS from weasyprint.text.fonts import FontConfiguration font_config = FontConfiguration() css_with_fonts = CSS(string=''' @font-face { font-family: 'CustomFont'; src: url('tests/resources/weasyprint.woff'); } body { font-family: 'CustomFont', sans-serif; } ''', font_config=font_config) HTML(string='<h1>中文标题</h1><p>这是中文内容...</p>').write_pdf( 'chinese_document.pdf', stylesheets=[css_with_fonts], font_config=font_config )实战应用场景
场景一:报表生成
企业级报表通常需要精确的表格布局:
def generate_report(data): table_rows = '' for item in data: table_rows += f''' <tr> <td>{item['name']}</td> <td>{item['value']}</td> <td>{item['date']}</td> </tr> ''' html_template = f''' <table style="width: 100%; border-collapse: collapse;"> <thead> <tr style="background-color: #f8f9fa;"> <th>项目</th> <th>数值</th> <th>日期</th> </tr> </thead> <tbody> {table_rows} </tbody> </table> ''' return HTML(string=html_template).write_pdf('report.pdf')场景二:电子书制作
制作精美的电子书需要分页控制和样式设计:
from weasyprint import HTML, CSS book_styles = CSS(string=''' @page { size: 6in 9in; margin: 0.5in; } @page :first { margin-top: 1in; } .chapter { page-break-before: always; } .page-number { position: running(pageNumber); } ''') # 分章节内容 chapters = ['第一章内容...', '第二章内容...'] full_content = '<div class="chapter">' + '</div><div class="chapter">'.join(chapters) + '</div>' HTML(string=full_content).write_pdf( 'ebook.pdf', stylesheets=[book_styles] )性能优化技巧
批量处理优化
处理大量文档时,保持Python进程运行:
from weasyprint import HTML def batch_generate_pdfs(html_files, output_dir): for filename in html_files: output_path = f"{output_dir}/{filename.replace('.html', '.pdf')}" HTML(filename).write_pdf(output_path)资源复用策略
复用字体配置和样式对象:
font_config = FontConfiguration() base_styles = CSS(string='base styles...', font_config=font_config) # 复用配置生成多个PDF for doc in documents: HTML(string=doc).write_pdf( f"output_{doc['id']}.pdf", stylesheets=[base_styles], font_config=font_config )常见问题解决方案
字体显示异常
确保系统安装了所需字体,或使用@font-face明确指定:
@font-face { font-family: 'MyFont'; src: url('tests/resources/weasyprint.otf') format('opentype'); }布局错乱处理
检查CSS兼容性,确保使用的CSS特性在WeasyPrint中受支持。
最佳实践总结
- 代码组织:将样式定义与内容生成分离,提高可维护性
- 错误处理:添加适当的异常捕获,确保生成过程稳定
- 质量检查:生成后验证PDF文件的完整性和可读性
通过本文的学习,您已经掌握了WeasyPrint的核心功能和实用技巧。无论是简单的文档转换还是复杂的企业级应用,WeasyPrint都能为您提供专业级的PDF生成解决方案。
【免费下载链接】WeasyPrintThe awesome document factory项目地址: https://gitcode.com/gh_mirrors/we/WeasyPrint
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考