close
要把一批檔案從 Word 檔轉成 PDF 檔,本來以為 "winword.exe" 可以有 command 驅動的參數,但是查了一下好像都是 PowerShell 的解法居多。
找到這篇是我覺得比較容易的做法:"PowerShell: Convert Word documents to PDF documents (Bulk)"(PowerShell: 批次將 Word 文件轉檔為 PDF 文件)。
function ConvertWordTo-PDF {
<#
.SYNOPSIS 概要
"ConvertTo-PDF" 這個函式是將 Word 檔轉為 PDF 檔
ConvertTo-PDF converts Microsoft Word documents to PDF files.
.DESCRIPTION 描述
這個 cmdlet 會查詢指定的來源目錄(包括其子目錄)裡面的 *.docx 與 *.doc 檔案,
把所有 Word 檔另存成 PDF 檔,存到指定的目的目錄裡。
指令完成後,Windows 的檔案總管會開啟目的目錄。
The cmdlet queries the given source folder including sub-folders to find *.docx and *.doc files,
converts all found files and saves them as pdf in the Destination folder. After completition, the Destination
folder with the newly created PDF files will be opened with Windows Explorer.
.PARAMETER SourceFolder 參數:來源目錄
必要參數 。請輸入你的 Word 檔來源目錄資料夾路徑。
Mandatory. Enter the source folder of your Microsoft Word documents.
.PARAMETER DestinationFolder 參數:目的目錄
可省略的參數 。輸入你指定的來源目錄以便將 PDF 儲存其中。
如果省略這個值,PDF 檔就會存在來源目錄裡。
Optional. Enter the Destination folder to save the created PDF documents. If you omit this parameter, pdf files will
be saved in the Source Folder.
.EXAMPLE 指令範例
ConvertWordTo-PDF -SourceFolder C:\Temp -DestinationFolder C:\Temp1
ConvertWordTo-PDF -SourceFolder C:\temp
.NOTES
作者:微軟 PowerShell MVP Patrick Gruenauer與他的個人網站
Author: Patrick Gruenauer | Microsoft PowerShell MVP [2018-2021]
Web: https://sid-500.com
#>
[CmdletBinding()]
param
(
[Parameter (Mandatory=$true,Position=0)]
[String]
$SourceFolder,
[Parameter (Position=1)]
[String]
$DestinationFolder = $SourceFolder
)
$i = 0
$word = New-Object -ComObject word.application
$FormatPDF = 17
$word.visible = $false
$types = '*.docx','*.doc'
If ((Test-Path $SourceFolder) -eq $false) {
throw "Error. Source Folder $SourceFolder not found." }
If ((Test-Path $DestinationFolder) -eq $false) {
throw "Error. Destination Folder $DestinationFolder not found." }
$files = Get-ChildItem -Path $SourceFolder -Include $Types -Recurse -ErrorAction Stop
''
Write-Warning "Converting Files to PDF ..."
''
foreach ($f in $files) {
$path = $DestinationFolder + '\' + $f.Name.Substring(0,($f.Name.LastIndexOf('.')))
$doc = $word.documents.open($f.FullName)
$doc.saveas($path,$FormatPDF)
$doc.close()
Write-Output "$($f.Name)"
$i++
}
''
Write-Output "$i file(s) converted."
Start-Sleep -Seconds 2
Invoke-Item $DestinationFolder
$word.Quit()
}
我自己的使用方法:
- 先打開一個 PowerShell 視窗。(在 Windows 左下角的搜尋框輸入 powershell 後按 Enter)
- 把上述的函式 "ConvertWordTo-PDF" 貼到 PowerShell 視窗,按下 Enter,該函式就定義完畢。
- 直接在同一個 PowerShell 視窗執行函式:
- 直接產製在同一目錄下:
ConvertWordTo-PDF -SourceFolder D:\Users\fanny\desktop\test - 產製到指定目錄(指定的目錄要先開好資料夾,以此例就是在桌面上把 "target" 這個資料夾先建立起來):
ConvertWordTo-PDF -SourceFolder D:\Users\fanny\desktop\test -DestinationFolder D:\Users\fanny\desktop\target
- 直接產製在同一目錄下:
稍等 PowerShell 跑一下(畫面上會印出已經開始轉檔的檔名),全部完成後,Windows 檔案總管會自動跳出該目錄。
打完收工~
文章標籤
全站熱搜
留言列表