17

PowerShell 小工具 - DOC 轉 DOCX/PDF 批次轉換

 3 years ago
source link: https://blog.darkthread.net/blog/ps-batch-conv-doc-to-docx/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
DOC 轉 DOCX/PDF 批次轉換-黑暗執行緒

去年分享過將 XLS 批次轉成 XLSX 的 PowerShell 小工具,有讀者問到如果是 DOC 轉 DOCX 要怎麼做?

PowerShell 小工具原理是啟動 Windows 上安裝的 Excel 軟體,控制它逐一讀檔,另存新檔,最後再關閉。若想處理 Word 就把 Excel 改成 Word,讀檔、存檔改用 Word 的 API 就可以。有 PowerShell、C# 或 VB 開發經驗,也會查微軟文件的程式老手,用膝蓋都能完成,但對沒相關經驗的人,渴望成功卻不知從何下手,或是一改就壞但無法理解錯在哪裡的無力感,我倒挺能體會。原因是這一兩年跨足自己不熟的 Arduino/ESP 開發板跟 C 語言,重新從菜鳥當起,有類似的體驗。

當然,練好基本功,按步就班是學習所有技能的正途,越級打怪之人也自知理虧,身為老鳥狂酸「先去唸好 XXX 吧 」、「YYY 網路教學很多,請自己爬文,乖」、「ZZZ 是基本常識耶」則是過頭了。對於沒相關經驗卻有動力想完成某些東西,態度也良好的朋友,我通常站在鼓勵的立場(自己走過類似的路,算同理心吧),目標過於崇高,或與能力落差過大,旁人愛莫能助;但若只是舉手之勞,我也想不出不幫的道理。

扯遠了。既然 DOC 轉 DOCX 也在某些人的許願清單上,將上次的程式小改幾行,DOC 轉 DOCX 批次轉換小工具就完成了! 希望它能讓地球某個角落的文件苦手早點下班。

Param(
    [parameter(Mandatory=$true, ValueFromRemainingArguments=$true)]
    [string]
    $docPaths, 
    [parameter(ValueFromPipelineByPropertyName=$true)]
    [switch][bool]
    $replace
)
$ErrorActionPreference = "STOP"
try 
{
    $doc = New-Object -ComObject Word.Application
    $doc.Visible = $true # 顯示 UI,方便使用者了解處理進度、輸入密碼等
    Get-Item $docPaths | ForEach-Object {
        $path = $_.FullName
        Write-Host "開啟 $path..."
        try {
            $doc.Documents.Open($path) | Out-Null
            $savePath =  $savePath = [System.IO.Path]::ChangeExtension($path, ".docx")
            # https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat
            # WdSaveFormat.wdFormatXMLDocument = 12
            $doc.ActiveDocument.SaveAs2($savePath, 12)
            $doc.ActiveDocument.Close()
            if ($replace) {
                Remove-Item $path                
            }
        }
        catch {
            Write-Host "發生錯誤 - $path" -ForegroundColor Red
        }
    }
}
finally 
{
    $doc.Quit()
}

實測成功。

[2022-02-12 更新]

貼文後再聽到有人許願,那可以轉 PDF 嗎?很簡單,SaveAs2 的參數由 12 改成 17 就可以了,如何知道是 17?可查微軟文件,裡面有不同格式的對映值。

我知道要求沒寫程式的朋友馬上搞懂這些也太難了,既然對我還是舉手之勞,就隨手附上 Convert-Doc2Pdf.ps1:(來源檔不限 doc,也可以是 docx )

Param(
    [parameter(Mandatory=$true, ValueFromRemainingArguments=$true)]
    [string]
    $docPaths, 
    [parameter(ValueFromPipelineByPropertyName=$true)]
    [switch][bool]
    $replace
)
$ErrorActionPreference = "STOP"
try 
{
    $doc = New-Object -ComObject Word.Application
    $doc.Visible = $true # 顯示 UI,方便使用者了解處理進度、輸入密碼等
    Get-Item $docPaths | ForEach-Object {
        $path = $_.FullName
        Write-Host "開啟 $path..."
        try {
            $doc.Documents.Open($path) | Out-Null
            $savePath = [System.IO.Path]::ChangeExtension($path, ".pdf")
            # https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat
            # WdSaveFormat.wdFormatPDF = 17
            $doc.ActiveDocument.SaveAs2($savePath, 17)
            $doc.ActiveDocument.Close()
            if ($replace) {
                Remove-Item $path                
            }
        }
        catch {
            Write-Host "發生錯誤 - $path" -ForegroundColor Red
        }
    }
}
finally 
{
    $doc.Quit()
}

簡單實測 OK,有需要的朋友請自取使用,並鼓勵大家認真考慮花點時間學會 PowerShell,讓你的人生變彩色。


Recommend

  • 10

    FreeBSD src 部份由 CVS 轉換到 Subversion這兩天在 #bsdchat 上有人提到目前 FreeBSD -src tree 準備要換到 Subversio...

  • 2

    VB Strings.StrConv 簡繁轉換撞字清單-黑暗執行緒 前幾天分享的 Oracle 改 MSSQL 出中文亂碼問題,我想出 VB.NET Strings.StrConv 做簡繁轉換的解法,進一步實測踩到一枚小地雷。

  • 14

    使用 PowerShell 批次設定 Excel 保護密碼-黑暗執行緒專案遇到為 Excel (.xlsx) 設定讀取密碼的需求。OpenXML SDK 提供的工作表保護功能,只僅限於防止內容被修改,無法做到輸入密...

  • 19

    集保罕用字轉換工具 .NET 飆速版-黑暗執行緒多年前研究過集保罕字集與 BIG5 造字,當時我用官方提供的編碼對照表(Map_code.txt)寫過一版 .NET 轉換函式。近期接到通報說

  • 8

    V2EX  ›  Android android 推荐的 编辑 Doc、PDF 的开源库不   honglei92 · 22 小时 14 分钟...

  • 15

    12 行 PowerShell 搞定批次下載 Podcast MP3-黑暗執行緒 最近慢跑聽膩 MP3 耳機裡現存的百年歌單,加上近幾個月都跑六分半配速,聽快節奏歌曲蠻不搭的,想抓些 Podcast 來聽解悶。 把 Podcast 抓成 MP3 的事兩年前

  • 6

    XLS 轉 XLSX 批次轉換-黑暗執行緒 Excel 2007 起開始推 XLSX 格式取代傳統 XLS,距今快 15 年了,XLS 大軍仍野火燒不盡,春風吹又生。一般使用者不太會知道二者差別,但也不至於刻意選 XLS 檔,現在仍在流傳的 XLS 檔很多是代代相傳,後人開啟更新後按儲存...

  • 10

    批次更換 Microsoft 365 授權的 PowerShell 腳本範例這幾天公司的 Office 365 授權要到期了,必須全員更換到 Microsoft 365 授權,由於現在人比較多,連在 Microsoft 365 admin center 想全選並

  • 17
    • blog.darkthread.net 3 years ago
    • Cache

    LibreOffice docx 轉 pdf 評估筆記

    LibreOffice docx 轉 pdf 評估筆記 2018-07-04 11:38 PM 13 11,186 我有寫了一個 Word 套表服務,最早是

  • 6

    Blog Post PDF vs. DOCX: How Textual Contents Can Be So Different In everyday business, it’s common for people to convert between Word documents and PDFs. And though PDFs can be very expressive and p...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK