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.
Nobody answers, I will refer to the example code of the clipboard in pywin32 to write it myself.
PYTHON Refer to link: https://gist.github.com/Erreinion/6691093
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)
src = win32clipboard.GetClipboardData(CF_HTML)
src = src.decode("UTF-8")
print(src)
else:
print("No RTF content")
OR
pip install klembord
The author of kembord is not correctly fetching the clipboard. Please 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])