社区检测技术演进与HPMOCD多目标优化实践
2026/5/24 6:36:11
【免费下载链接】WeasyPrintThe awesome document factory项目地址: https://gitcode.com/gh_mirrors/we/WeasyPrint
WeasyPrint是一个强大的Python工具,能够将HTML和CSS文档转换为高质量的PDF文件。无论您需要生成报告、发票还是其他文档,这个开源项目都能提供专业的解决方案。
在安装WeasyPrint之前,请确保您的系统满足以下要求:
最简单的安装方式是使用pip:
pip install weasyprint对于不同的操作系统,还有更便捷的安装方式:
Linux用户:
# Ubuntu/Debian sudo apt install weasyprint # Fedora sudo dnf install weasyprintmacOS用户:
brew install weasyprintWeasyPrint提供了简单易用的命令行工具:
# 从HTML文件生成PDF weasyprint input.html output.pdf # 添加自定义样式 weasyprint input.html output.pdf -s style.css在Python代码中使用WeasyPrint更加灵活:
from weasyprint import HTML # 从URL生成PDF HTML('https://example.com').write_pdf('output.pdf') # 从HTML字符串生成PDF html_content = ''' <!DOCTYPE html> <html> <head> <style> body { font-family: Arial; margin: 20px; } h1 { color: #333; } </style> </head> <body> <h1>我的文档标题</h1> <p>这里是文档内容...</p> </body> </html> ''' HTML(string=html_content).write_pdf('my_document.pdf')from weasyprint import HTML, CSS from weasyprint.text.fonts import FontConfiguration font_config = FontConfiguration() css = CSS(string=''' @font-face { font-family: 'MyFont'; src: url('/path/to/font.ttf'); } body { font-family: 'MyFont', sans-serif; } ''', font_config=font_config) HTML('input.html').write_pdf( 'output.pdf', stylesheets=[css], font_config=font_config )document = HTML('input.html').render() # 获取奇数页 odd_pages = document.copy(document.pages[::2]) odd_pages.write_pdf('odd_pages.pdf') # 获取偶数页 even_pages = document.copy(document.pages[1::2]) even_pages.write_pdf('even_pages.pdf')问题1:依赖库缺失如果遇到安装错误,可以尝试安装系统级依赖:
# Ubuntu/Debian sudo apt install libpango1.0-0 libcairo2 # 或者重新安装 pip uninstall weasyprint pip install weasyprint问题2:字体显示异常确保系统安装了所需字体,或者使用@font-face明确指定字体路径。
from weasyprint import HTML def generate_report(data): html_template = f''' <html> <head><style> .header {{ background: #f0f0f0; padding: 20px; }} .content {{ margin: 20px; }} </style></head> <body> <div class="header"> <h1>业务报告 - {data['date']}</h1> </div> <div class="content"> <p>总销售额: {data['sales']}</p> <p>增长率: {data['growth']}%</p> </div> </body> </html> ''' HTML(string=html_template).write_pdf(f"report_{data['date']}.pdf")def create_invoice(invoice_data): html = f''' <div style="font-family: Arial; max-width: 800px; margin: 0 auto;"> <h1 style="text-align: center;">发票</h1> <table style="width: 100%; border-collapse: collapse;"> <tr><th>项目</th><th>数量</th><th>单价</th><th>总价</th></tr> {''.join(f'<tr><td>{item["name"]}</td><td>{item["quantity"]}</td><td>{item["price"]}</td><td>{item["total"]}</td></tr>' for item in invoice_data['items'])} </table> </div> ''' HTML(string=html).write_pdf(f"invoice_{invoice_data['number']}.pdf")处理用户提交的HTML内容时,请注意以下安全事项:
想要深入掌握WeasyPrint,建议按以下步骤学习:
通过本指南的学习,您已经掌握了WeasyPrint的核心使用方法。这个强大的工具能够帮助您轻松实现各种文档转换需求,从简单的网页转换到复杂的业务报表生成,都能得心应手。
现在就开始尝试使用WeasyPrint创建您的第一个PDF文档吧!
【免费下载链接】WeasyPrintThe awesome document factory项目地址: https://gitcode.com/gh_mirrors/we/WeasyPrint
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考