上一篇
Python HTML转PDF教程:多种方法实现网页转PDF文件 - 技术博客
- Python
- 2025-08-07
- 316
Python实现HTML转PDF的完整教程
多种方法实现网页内容到PDF文件的转换
为什么需要HTML转PDF?
在Python开发中,将HTML内容转换为PDF的需求非常常见,主要应用场景包括:
- 自动生成报告或发票
- 保存网页内容为PDF文件
- 创建电子书或文档
- 实现打印预览功能
- 存档重要网页内容
方法一:使用wkhtmltopdf + pdfkit
这是最常用的HTML转PDF方法之一,基于Qt WebKit渲染引擎。
安装步骤
pip install pdfkit
# 同时需要安装wkhtmltopdf程序
# Windows:下载安装包
# Ubuntu/Debian:sudo apt-get install wkhtmltopdf
# macOS:brew install homebrew/cask/wkhtmltopdf
# 同时需要安装wkhtmltopdf程序
# Windows:下载安装包
# Ubuntu/Debian:sudo apt-get install wkhtmltopdf
# macOS:brew install homebrew/cask/wkhtmltopdf
示例代码
import pdfkit
# 配置wkhtmltopdf路径(Windows可能需要指定路径)
config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')
# 从URL转换
pdfkit.from_url('http://example.com', 'output1.pdf', configuration=config)
# 从HTML文件转换
pdfkit.from_file('input.html', 'output2.pdf', configuration=config)
# 从HTML字符串转换
html_content = '''
<html>
<head><title>Test</title></head>
<body>
<h1>Hello PDF!</h1>
<p>This is a test document.</p>
</body>
</html>
'''
pdfkit.from_string(html_content, 'output3.pdf', configuration=config)
优缺点
优点 | 缺点 |
---|---|
转换质量高 | 需要安装外部程序 |
支持CSS和JavaScript | 内存占用较高 |
支持多种输入源 | 对中文支持需要配置字体 |
方法二:使用WeasyPrint
纯Python实现的HTML转PDF解决方案,无需外部依赖。
安装步骤
pip install weasyprint
示例代码
from weasyprint import HTML
# 从HTML文件生成PDF
HTML('input.html').write_pdf('output.pdf')
# 从URL生成PDF
HTML('http://example.com').write_pdf('url_output.pdf')
# 从HTML字符串生成PDF
html_content = '''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>body { font-family: Arial; }</style>
</head>
<body>
<h1>WeasyPrint示例</h1>
<p>这是一个使用WeasyPrint生成的PDF文件。</p>
</body>
</html>
'''
HTML(string=html_content).write_pdf('string_output.pdf')
优缺点
优点 | 缺点 |
---|---|
纯Python实现 | 不支持JavaScript |
安装简单 | CSS支持有限 |
支持CSS分页媒体 | 复杂页面渲染可能不完美 |
方法三:使用Pyppeteer(无头Chrome)
使用Headless Chrome浏览器进行HTML渲染后生成PDF。
安装步骤
pip install pyppeteer
示例代码
import asyncio
from pyppeteer import launch
async def generate_pdf():
browser = await launch()
page = await browser.newPage()
# 从URL生成PDF
await page.goto('http://example.com', {'waitUntil': 'networkidle0'})
await page.pdf({'path': 'url_output.pdf', 'format': 'A4'})
# 从HTML内容生成PDF
html_content = '''
<html>
<body>
<h1>Pyppeteer PDF生成</h1>
<p>使用Headless Chrome生成的PDF文档</p>
</body>
</html>
'''
await page.setContent(html_content)
await page.pdf({'path': 'content_output.pdf', 'format': 'A4'})
await browser.close()
# 运行异步函数
asyncio.get_event_loop().run_until_complete(generate_pdf())
优缺点
优点 | 缺点 |
---|---|
渲染效果最接近浏览器 | 需要安装Chromium |
完美支持JavaScript | 启动速度较慢 |
支持现代CSS特性 | 内存占用最高 |
方法对比与选择建议
wkhtmltopdf
适合:需要高质量打印效果的场景
不适合:资源受限的环境
WeasyPrint
适合:简单内容快速转换
不适合:包含JavaScript的页面
Pyppeteer
适合:现代网页和SPA应用
不适合:低配置服务器环境
中文支持注意事项
- 确保在HTML中指定正确的字符集:<meta charset="UTF-8">
- 在CSS中指定中文字体:
body { font-family: 'Noto Sans SC', 'Microsoft YaHei', sans-serif; } - 对于wkhtmltopdf,可能需要添加
--encoding 'UTF-8'
参数 - 在服务器环境部署时,确保安装了中文字体
本文由YanRanJie于2025-08-07发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://www.521pj.cn/20257554.html
发表评论