You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Bash终端将Word按指定布局(页面大小、边距)保存为PDF?

用Bash实现Word文件按自定义布局导出PDF

你的AppleScript每次MacOS更新后失效,核心原因是依赖GUI控件的定位操作(比如点击菜单、按钮),系统更新后控件结构常发生变化。用Bash结合osascript调用Word的原生脚本API,可以避开不稳定的GUI模拟,实现更可靠的导出。

实现方案

前提

确保你需要的页面布局已经在Word中保存为预设(比如你原脚本里的"custom")。

示例Bash脚本

#!/bin/bash

# 配置路径和布局名称
INPUT_DOC="/Users/xxx/your-document.docx"  # 替换为你的Word文件路径
OUTPUT_PDF="/Users/xxx/exported.pdf"       # 替换为输出PDF路径
CUSTOM_PRESET="custom"                     # 替换为你的自定义布局预设名

# 调用Word的脚本API完成导出
osascript <<EOF
tell application "Microsoft Word"
    -- 打开目标文档
    set targetDoc to open POSIX file "$INPUT_DOC"
    -- 应用自定义页面布局预设
    set page setup of targetDoc to page setup preset "$CUSTOM_PRESET"
    -- 导出为PDF
    save as targetDoc file name POSIX file "$OUTPUT_PDF" file format format PDF
    -- 关闭文档(可选,若不需要保留打开状态)
    close targetDoc saving no
end tell
EOF

处理已打开的文档

如果要处理当前Word中已激活的文档,可简化脚本:

#!/bin/bash

OUTPUT_PDF="/Users/xxx/exported.pdf"
CUSTOM_PRESET="custom"

osascript <<EOF
tell application "Microsoft Word"
    set activeDoc to active document
    set page setup of activeDoc to page setup preset "$CUSTOM_PRESET"
    save as activeDoc file name POSIX file "$OUTPUT_PDF" file format format PDF
end tell
EOF

优势

  • 直接调用Word的官方脚本接口,不依赖GUI元素定位,MacOS更新后不会失效
  • 运行过程无需激活Word窗口,可后台执行
  • 脚本逻辑清晰,便于修改扩展

内容的提问来源于stack exchange,提问作者Caterina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 02:27:44