You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中从剪贴板粘贴富文本?(Windows 11环境)

解决Windows下从Word剪贴板读取富文本格式的问题

Windows剪贴板中,Microsoft Word复制的富文本内容会以RTF(Rich Text Format)或HTML格式存储,而非仅纯文本。pyclip默认读取的是纯文本格式,因此会丢失加粗、斜体等样式信息。要获取完整格式,需要直接读取剪贴板中的RTF或HTML数据。

方法1:读取剪贴板中的RTF格式数据

使用pywin32库的win32clipboard模块,直接读取RTF格式的剪贴板内容:

首先安装依赖:

pip install pywin32

示例代码:

import win32clipboard
import win32con

def get_clipboard_rtf():
    win32clipboard.OpenClipboard()
    try:
        # 检查剪贴板是否有RTF格式数据
        if win32clipboard.IsClipboardFormatAvailable(win32con.CF_RTF):
            rtf_data = win32clipboard.GetClipboardData(win32con.CF_RTF)
            return rtf_data
        else:
            return "剪贴板中无RTF格式数据"
    finally:
        win32clipboard.CloseClipboard()

# 调用示例
rtf_content = get_clipboard_rtf()
print(rtf_content)

从Word复制加粗文本后,运行这段代码会输出包含样式标记的RTF内容,比如:

{\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Calibri;}}{\colortbl ;\red0\green0\blue0;}{*\generator Msftedit 5.41.21.2510;}\viewkind4\uc1\pard\sa200\sl276\slmult1\f0\fs22 This is \b bold text\b0 in a Word document.\par}

方法2:读取剪贴板中的HTML格式数据

部分应用(包括Word)也会将富文本以HTML格式写入剪贴板,读取方式类似:

import win32clipboard
import win32con

def get_clipboard_html():
    win32clipboard.OpenClipboard()
    try:
        # HTML格式的剪贴板标识是CF_HTML,需要自定义注册
        CF_HTML = win32clipboard.RegisterClipboardFormat("HTML Format")
        if win32clipboard.IsClipboardFormatAvailable(CF_HTML):
            html_data = win32clipboard.GetClipboardData(CF_HTML).decode('utf-8')
            # 提取有效HTML部分(剪贴板中的HTML包含头部信息)
            start_idx = html_data.find("<!--StartFragment-->") + len("<!--StartFragment-->")
            end_idx = html_data.find("<!--EndFragment-->")
            return html_data[start_idx:end_idx].strip()
        else:
            return "剪贴板中无HTML格式数据"
    finally:
        win32clipboard.CloseClipboard()

# 调用示例
html_content = get_clipboard_html()
print(html_content)

运行后会输出带HTML标签的内容:

This is bold text in a Word document.

解析RTF为HTML(可选)

如果需要将RTF转换为更易处理的HTML,可以使用rtf2html库:

安装依赖:

pip install rtf2html

示例代码:

from rtf2html import rtf_to_html

rtf_content = get_clipboard_rtf()
html_content = rtf_to_html(rtf_content)
print(html_content)

这样就能得到结构化的HTML内容,方便在你的应用中使用。

内容的提问来源于stack exchange,提问作者Gaspar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 04:43:32