How can I retrieve rich text format content from the clipboard in Python after copying it from Excel or HTML?
I tried pyperclip and clipboard python package, but they only output plain text.
I would like Python to directly output rich text formatted content, not just plain text content.
Based on the example code of the clipboard in pywin32:
import win32clipboard
def GetAvailableFormats():
"""
Return a possibly empty list of formats available on the clipboard
"""
formats = []
try:
win32clipboard.OpenClipboard(0)
cf = win32clipboard.EnumClipboardFormats(0)
while (cf != 0):
formats.append(cf)
cf = win32clipboard.EnumClipboardFormats(cf)
finally:
win32clipboard.CloseClipboard()
return formats
# CF_HTML=49433
CF_HTML = win32clipboard.RegisterClipboardFormat("HTML Format")
if CF_HTML in GetAvailableFormats():
win32clipboard.OpenClipboard(0)
try:
src = win32clipboard.GetClipboardData(CF_HTML)
src = src.decode("UTF-8")
print(src)
finally:
win32clipboard.CloseClipboard()
else:
print("No RTF content")
OR
pip install klembord
The author of klembord is not correctly fetching the clipboard. Modify the html = html.decode(UTF8)[131:-38]
line in the get_with_rich_text
method of __init__.py
as:
from re import search
html = search("<html>([\\s\\S]+)</html>",html.decode(UTF8)).group(0)
example code:
import klembord
# copy content
klembord.set_with_rich_text('Hello, world!', '<h1>Hello, world!</h1>')
# print content
print(klembord.get_with_rich_text()[1])