Search code examples
macosservicertf

Create new rtf file as a service on MacOS


I regularly use this service to create a new text file in the currently opened folder:

tell application "Finder"
    set txt to make new file at (the target of the front window) as alias
    select txt
end tell

But it would be much more useful if I could create an RTF instead. Yet after googling and GPT'ing, I can't get it to work. Anyone that has written a similar service for themselves?


Solution

  • It's not super elegant but you can write the data of an empty RTF document to your newly-created file:

    tell application "Finder" to set txt to (make new file at Finder window 1) as alias
    try
        set fileHandle to open for access (POSIX path of txt) with write permission
        write "{\\rtf1\\ansi\\ansicpg1252\\cocoartf2757
    \\cocoatextscaling0\\cocoaplatform0{\\fonttbl}
    {\\colortbl;\\red255\\green255\\blue255;}
    {\\*\\expandedcolortbl;;}
    \\paperw11900\\paperh16840\\margl1440\\margr1440\\vieww11520\\viewh8400\\viewkind0
    }" to fileHandle
        close access fileHandle
    on error err number num
        display dialog err & " number " & num buttons {"OK"} default button 1 with title "File I/O Error..." with icon caution
        try
            close access fileHandle
        end try
        return
    end try
    
    tell application "Finder" to select txt
    

    This will result in a functioning RTF if you open it in TextEdit.