The Omni Group Forums

The Omni Group Forums (http://forums.omnigroup.com/index.php)
-   AppleScripting Omni Apps (http://forums.omnigroup.com/forumdisplay.php?f=46)
-   -   Getting RTF and HTML strings from formatted text in the Clipboard (http://forums.omnigroup.com/showthread.php?t=18784)

RobTrew 2010-11-01 01:56 PM

Getting RTF and HTML strings from formatted text in the Clipboard
 
Applescript is ill-equipped to transform formatted text.

(Assigning a text/string variable to a stretch of formatted text coerces it to plain text).

There is sometimes scope for working around this limitation by getting the formatted text into the clipboard, from which it is possible to extract RTF or HTML strings. You can transform these strings, and then put modified formatted text back into the clipboard with pbcopy.

Some illustrative code:

[CODE]property pstrTempFile : "tmp.rtf"

tell application id "com.apple.finder"

-- TRY TO GET SOME RTF DATA FROM THE CLIPBOARD
try
set dataRTF to the clipboard as «class RTF »
on error
display dialog "No RTF in clipboard ..." with title "Get RTF & HTML strings"
return
end try

-- RETRIEVE THE RAW RTF STRINGS INTO AN APPLESCRIPT VARIABLE USING PBPASTE
-- (PBCOPY can be used later to put a transformed version back into the clipboard)
set the clipboard to dataRTF
set strRTF to do shell script "pbpaste -Prefer rtf"


-- WRITE THE RTF OUT TO A TEMPORARY FILE
set strTempFolder to (container of (path to me)) as string
set strTempFile to strTempFolder & pstrTempFile
set oFile to strTempFile as file specification
open for access oFile with write permission
write dataRTF to oFile as «class RTF »
close access oFile

-- USE TEXTUTIL TO GET AN HTML VERSION OF THE RTF
-- (HTML can be easier to read and transform,
-- and TEXTUTIL can be used again later to convert from HTML back to RTF)
set strTempFile to POSIX path of strTempFile
set strHTML to do shell script "textutil -convert html -stdout " & strTempFile

{strRTF, strHTML}
end tell[/CODE]


All times are GMT -8. The time now is 01:08 PM.

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2020, vBulletin Solutions, Inc.