python --html转word

试了pdf2docx pdf转word 样式保留太差

试了liboffice pdf转word 样式保留太差

只有微软的office接口 和 浏览器渲染复制的情况 样式目前还行 能接受

python 复制代码
# 必须有微软的office 否则不可执行
def html_to_word_copy_paste(html_path):
    """
    纯模拟真实Ctrl+A/C按键 → 粘贴到Word(保留100%浏览器样式)
    """
    # 1. 初始化Chrome(关闭自动化提示,避免权限拦截)
    options = webdriver.ChromeOptions()
    options.add_argument("--start-maximized")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_experimental_option('useAutomationExtension', False)


    service = Service(executable_path=DRIVER_PATH)
    driver = webdriver.Chrome(service=service, options=options)


    try:
        # 2. 打开本地HTML文件(确保路径正确)
        abs_html_path = os.path.abspath(html_path).replace("\\", "/")
        html_url = f"file:///{abs_html_path}"
        driver.get(html_url)
        time.sleep(3)  # 等待页面+CSS+图片完全渲染

        # 3. 【核心修复】用Keys常量模拟真实Ctrl+A(解决编码报错)
        # 先聚焦页面,避免按键失效
        driver.find_element("tag name", "body").click()
        # 全选:Ctrl+A(用Keys模块传递标准按键指令)
        driver.find_element("tag name", "body").send_keys(Keys.CONTROL, "a")
        time.sleep(1)
        logger.debug("✅ 已执行Ctrl+A全选内容")

        # 4. 复制:Ctrl+C(同样用Keys模块)
        driver.find_element("tag name", "body").send_keys(Keys.CONTROL, "c")
        time.sleep(1)
        logger.debug("✅ 已执行Ctrl+C复制内容到剪贴板")

        # 5. Word粘贴(强制保留HTML源格式)
        word = win32.Dispatch("Word.Application")
        word.Visible = True
        doc = word.Documents.Add()

        # 粘贴核心代码(保留所有样式:字体/行距/表格/图片)
        doc.Content.PasteSpecial(
            Link=False,
            DisplayAsIcon=False,
            DataType=10,  # 10 = HTML Format,和手动粘贴"保留源格式"一致
            Placement=0,
            IconIndex=0
        )
        logger.debug("✅ 已粘贴到Word(保留浏览器原始样式)")

        docx_abs_path = os.path.join(MEDIA_DIR, create_random_file_name('.docx'))  # docx保存的绝对路径
        # 6. 保存并清理
        doc.SaveAs2(docx_abs_path, FileFormat=16)
        doc.Close()
        word.Quit()
        logger.success(f"html转docx转换完成!文件:{docx_abs_path}")
        return docx_abs_path

    except Exception as e:
        logger.error(f"❌ 失败原因:{str(e)}")
        return ''

    finally:
        driver.quit()
相关推荐
阿耶同学1 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田17 小时前
Pydantic校验配置文件
python
hboot17 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉
韩师傅2 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉