python四种方式实现html文件转word、pdf文档或图片
ai大模型可以生成各种各样的设计页面,包括海报、ui界面、简历等你能看到的一切设计,但是没办法直接生成pdf、word等电子文档,如果我们可以将html代码转成word文档,那岂不是ai就能生成各种精美好看大气的文档了。
python有四种方式可以将htm代码文件转换成word文档图片等形式,最后一种最好,与html显示效果一致。

1、BeautifulSoup++Document
from bs4 import BeautifulSoup
from docx import Document
import sys
def html_to_word(html_file: str, output_file: str):
"""将 HTML 文件转换为 Word 文档"""
# 读取 HTML 文件
with open(html_file, 'r', encoding='utf-8') as f:
html_content = f.read()
soup = BeautifulSoup(html_content, 'html.parser')
# 创建一个空白的 Word 文档
doc = Document()
# 如果有 <title> 标签,则添加标题
if soup.title:
doc.add_heading(soup.title.string, level=1)
# 将 <h1> ~ <h6> 标签内容添加为标题
for tag_name in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']:
for tag in soup.find_all(tag_name):
# 去掉前后空白,并以标签名称决定标题级别
text = tag.get_text(strip=True)
if text:
level = int(tag_name[1])
doc.add_heading(text, level=level)
# 将 <p> 和 <div> 标签内容添加为段落
for tag in soup.find_all(['p', 'div']):
text = tag.get_text(strip=True)
if text:
doc.add_paragraph(text)
# 保存 Word 文档
doc.save(output_file)
print(f"转换成功,文件保存为:{output_file}")
if __name__ == "__main__":
if len(sys.argv) != 3:
print("用法: python htmltoword.py input.html output.docx")
sys.exit(1)
html_to_word(sys.argv[1], sys.argv[2])
这种方式能将html转成word,但是样式跟原来的html有差异2、weasyprint
from selenium import webdriver
from docx import Document
from weasyprint import HTML
import pdfkit
import imgkit
import os
class HTMLConverter:
def __init__(self):
"""初始化转换器"""
# Chrome headless模式配置
self.chrome_options = webdriver.ChromeOptions()
self.chrome_options.add_argument('--headless')
self.chrome_options.add_argument('--disable-gpu')
def to_image(self, html_path: str, output_path: str):
"""将HTML转换为图片
Args:
html_path: HTML文件路径
output_path: 输出图片路径(.png/.jpg)
"""
# 使用imgkit
options = {
'quality': 100,
'form...点击查看剩余70%
网友评论0