简体   繁体   中英

How to copy Rich Text Format to clipboard with python

I want to copy rich text format to the clipboard in windows. Here's what I've got:

import win32clipboard

CF_RTF = win32clipboard.RegisterClipboardFormat("Rich Text Format")

rtf = r"{\rtf1\ansi\deff0 {\pard This is a test\par}}"

win32clipboard.OpenClipboard(0)
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(CF_RTF, rtf)
win32clipboard.CloseClipboard()

When I run this, and paste the output into word, it is not formatted correctly:

在此处输入图片说明

Convert it to a bytearray like this:

import win32clipboard

CF_RTF = win32clipboard.RegisterClipboardFormat("Rich Text Format")


rtf = bytearray("{\\rtf1\\ansi\\deff0 {\\pard This is a test\\par}}", 'utf8')

win32clipboard.OpenClipboard(0)
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(CF_RTF, rtf)
win32clipboard.CloseClipboard()

On Linux:

import sys
import subprocess

def copy_rtf(string):
    if str(type(string)) == "<class 'str'>":
        string = bytearray(string, 'utf8')
    subprocess.Popen(['xclip', '-selection', 'clipboard', '-t', 'text/rtf'], stdin=subprocess.PIPE).communicate(string)

text = r"{\rtf1\ansi\deff0 {\b This} is some text\row}"

copy_rtf(text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM