Manipulate Styled Text on Clipboard

Posted on March 6, 2012
Filed Under Applescript, Automation, Python | 1 Comment

One thing that Appscript doesn’t let you do easily is handle styled text from the clipboard in Python. (This isn’t Appscript’s fault of course – it wasn’t intended to) Putting styled text on the clipboard isn’t hard. I had a script I discussed last fall that does that. I use that script a lot to put styled tables on the clipboard.

The below is a short script that gets the styled text off the clipboard and then converts it to HTML (which is easier to manipulated than rtf). Please consider this just a “how to” script and not a fully functional script you’d use. For one thing if the text on the clipboard isn’t styled then this returns nothing. (Say it was plain text) Normally that’s not what you’d want to do. It also doesn’t check for HTML text rather than rtf text. I did that simply because Safari puts rtf text on the clipboard rather than HTML. But it’d be trivial to modify the below to check for HTML as well. This is more just showing how to do it since there was nothing I could find online that demonstrated this.

I’ll put some scripts out in the future that leverage the below for more useful purposes.

#!/usr/bin/env python
 
import sys
from Foundation import *
from AppKit import *
import re, os, subprocess
 
## Get any rtf data off the clipboard
 
def getrtfclipboard():
    pb = NSPasteboard.generalPasteboard()
    type = pb.availableTypeFromArray_([NSPasteboardTypeRTF]) #specify rtf type
    data = None
    if type is not None:
        data = pb.stringForType_(type) # get the data as text
        return data
 
def convertrtf(path):
    q = "textutil -convert html " + path
    subprocess.call(q, shell=True)
 
    newpath = os.path.splitext(path)[0] + ".html"
 
    data = None
    f = open(newpath, "r")
    try:
        data = f.read()
    finally:
        f.close()
 
    os.remove(newpath)
    return data
 
def convertohtml(data):
    if data is None:
        print "****ERROR"
        return
 
    path = "/tmp/pb.%s.rtf" % os.getpid()
    f = open(path, 'w+t')
    try:
        f.write(data)
    finally:
        f.close()
 
    newdata = convertrtf(path)
    os.remove(path)
    return newdata
 
def sethtmlclipboard(html):
    pb = NSPasteboard.generalPasteboard()
    a = NSArray.arrayWithObject_(NSHTMLPboardType)
    pb.declareTypes_owner_(a, None)
    pb.setString_forType_( html, NSHTMLPboardType)
 
 
 
def main():
    data = getrtfclipboard()
    print data
    newdata = convertohtml(data)
    print newdata
 
if __name__ == '__main__':
    main()
 
    # change to 0 for success, 1 for (partial) failure
    sys.exit(0)

Comments

One Response to “Manipulate Styled Text on Clipboard”

[...] Nice work by Clark to manipulate text on the pasteboard via pyObjC. [...]

Leave a Reply