求助:在macOS上实现创建RTF文件的服务
在Finder当前文件夹创建RTF文件的AppleScript服务方案
下面提供两种可行的AppleScript方案,替代你原来的纯文本文件创建脚本:
方案1:直接写入RTF格式内容(无需依赖TextEdit)
这种方法通过生成符合RTF规范的空内容并写入文件,避免调用其他应用,运行更轻量化:
tell application "Finder" set targetFolder to target of front window as alias end tell -- 定义空RTF文件的标准格式内容 set rtfContent to "{\\rtf1\\ansi\\ansicpg1252\\cocoartf2708 \\cocoatextscaling0\\cocoaplatform0{\\fonttbl\\f0\\fswiss\\fcharset0 Helvetica;} {\\colortbl;\\red255\\green255\\blue255;} {\\*\\expandedcolortbl;;} \\pard\\tx560\\tx1120\\tx1680\\tx2240\\tx2800\\tx3360\\tx3920\\tx4480\\tx5040\\tx5600\\tx6160\\tx6720\\pardirnatural\\partightenfactor0 \\f0\\fs24 \\cf0 }" -- 设置默认文件名,可根据需求修改 set defaultFileName to "Untitled.rtf" set newFilePath to (targetFolder as text) & defaultFileName -- 写入文件并处理可能的错误 try set fileReference to open for access file newFilePath with write permission write rtfContent to fileReference as «class utf8» close access fileReference -- 在Finder中选中新生成的RTF文件 tell application "Finder" select file newFilePath end tell on error errorMessage try close access file newFilePath end try display dialog "创建RTF文件失败: " & errorMessage buttons {"确定"} default button 1 end try
方案2:借助TextEdit创建原生RTF文件
这种方法调用系统自带的TextEdit来创建并保存RTF文件,生成的文件和手动通过TextEdit创建的格式完全一致:
tell application "Finder" set targetFolder to target of front window as alias end tell tell application "TextEdit" set newRTFDocument to make new document save newRTFDocument in targetFolder as rich text with properties {name:"Untitled.rtf"} close newRTFDocument end tell -- 在Finder中定位并选中新文件 tell application "Finder" select file (targetFolder as text) & "Untitled.rtf" end tell
说明
你原来的脚本使用Finder的make new file方法时,默认调用的是系统的"Empty File"模板,只能生成纯文本文件(.txt)。RTF属于富文本格式,需要明确生成对应格式的内容或借助支持富文本的应用来创建。
内容的提问来源于stack exchange,提问作者PeterPefi
相关产品推荐
相关产品推荐

