从终端将 Word 保存为具有特定布局(页面大小和边距)的 PDF

问题描述 投票:0回答:1

到目前为止,我一直以这种方式保存我的 Word 文件:

set outpath to "/Users/..."

-- This part gets rid of the grant access problem
set sd to path to startup disk
tell application id "com.microsoft.Word"
    try
        close sd
    end try
end tell

tell application "Microsoft Word"
    activate
end tell

--Saving word Document to PDF
tell application "System Events"
    delay 0.2
    keystroke "a" using command down
    tell application process "Microsoft Word"
        click menu item "Page Setup..." of menu "File" of menu bar item "File" of menu bar 1
        delay 0.2
        click pop up button 2 of window "Page Setup"
        keystroke "CutomSize"
        delay 0.2
        keystroke return
        delay 0.2
        keystroke return
        delay 0.2
    end tell
end tell

tell application "Microsoft Word"
    set activeDoc to active document
    save as activeDoc file name outpath file format format PDF
end tell

问题是这段代码随着 MacOS 的每次更新而中断。有没有办法用 bash 从终端做到这一点?

pdf applescript word
1个回答
0
投票

AppleScript Objective-C (AsObjC) 可以做到这一点。以下大部分代码由@Shane Stanley 编写,我进行了少量改编。您可以使用 osascript 命令轻松将此代码转换为终端命令,但为什么不按原样使用它呢?

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

-- dimensions of print area:
property thePaperSize : {height:842.0, width:595.0}
property theLeft : 72.0
property theRight : 72.0
property theTop : 90.0
property theBottom : 90.0

-- choose Word document file, make URL and build destination path
set posixPath to POSIX path of (choose file of type {"doc", "docx"})
set theURL to current application's |NSURL|'s fileURLWithPath:posixPath
set destPath to theURL's |path|()'s stringByDeletingPathExtension()'s stringByAppendingPathExtension:"pdf"

-- get doc's contents as styled text
set {styledText, theError} to current application's NSAttributedString's alloc()'s initWithURL:theURL options:(missing value) documentAttributes:(missing value) |error|:(reference)
if styledText = missing value then error (theError's localizedDescription() as text)

-- set up printing specs
set printInf to current application's NSPrintInfo's sharedPrintInfo()'s |copy|()
printInf's setJobDisposition:(current application's NSPrintSaveJob)
printInf's dictionary()'s setObject:destPath forKey:(current application's NSPrintSavePath)

-- make text view and add text
set theView to current application's NSTextView's alloc()'s initWithFrame:{{0, 0}, {(width of thePaperSize) - theLeft - theRight, (height of thePaperSize) - theTop - theBottom}}
theView's textStorage()'s setAttributedString:styledText

-- set up and run print operation without showing dialog
set theOp to current application's NSPrintOperation's printOperationWithView:theView printInfo:printInf
theOp's setShowsPrintPanel:false
theOp's setShowsProgressPanel:false
theOp's runOperation()
© www.soinside.com 2019 - 2024. All rights reserved.