没有更多的废话,直接上代码,代码的注释应该很清楚了。
property word_docs : {"org.openxmlformats.wordprocessingml.document", "com.microsoft.word.doc"}
property default_path : (path to desktop) as alias
property Delim : {".docx", ".doc"}
property PDF : ".pdf"
set outPDF to {}
-- 打开文件选择对话框,只允许选择Word文档,并将所选文件存储在变量 selected_files 中
set selected_files to (choose file of type word_docs default location default_path with multiple selections allowed without invisibles and showing package contents)
-- 将Word文档的扩展名替换为PDF,并将PDF文件路径添加到 outPDF 列表中
set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, Delim}
repeat with afile in selected_files
copy item 1 of text items of (afile as text) & PDF to the end of outPDF
end repeat
set AppleScript's text item delimiters to TID
-- 使用Microsoft Word应用程序对象
tell application id "com.microsoft.Word"
-- 将Microsoft Word窗口设置为活动窗口
activate
-- 循环遍历所选的Word文档
repeat with i from 1 to count of selected_files
-- 获取所选Word文档的POSIX路径
set theOriginalPath to POSIX path of (item i of selected_files)
-- 打开Word文档
open theOriginalPath
-- 等待0.5秒,以确保Word文档已完全打开
delay 0.5
-- 获取转换后的PDF文件的POSIX路径
set theOutputPath to POSIX path of (item i of outPDF)
-- 开始一个异常处理块,以处理Word文档访问权限请求的问题
try
-- 获取当前打开的Word文档对象
tell active document
-- 将Word文档另存为PDF文件
save as it file name theOutputPath file format format PDF
-- 关闭Word文档,并不保存更改
close saving no
end tell
on error err
-- 如果在保存Word文档为PDF文件时发生错误,则执行以下操作
-- 使用System Events应用程序对象
tell application "System Events"
-- 按下ESC键,以关闭访问权限请求窗口
key code 53
end tell
-- 等待2秒钟,以确保访问权限请求窗口已关闭
delay 2
-- 获取当前打开的Word文档对象
tell active document
-- 将Word文档另存为PDF文件
save as it file name theOutputPath file format format PDF
-- 关闭Word文档,并不保存更改
close saving no
end tell
end try
end repeat
end tell
-- 返回转换后的PDF文件路径列表
return outPDF