YouTube_Wordを開かず一瞬でPDF化する方法【AutoHotkey】

YouTubeでお伝えしたAutoHotekeyのコードはこちらです。

ご活用いただければ。

コード詳細
#Requires AutoHotkey v2.0
#SingleInstance Force

; ============================================================
; Explorerで選択したWordファイルをPDF化
;
; 操作
;   Explorerで .doc / .docx を選択F8
;
; 仕様
;   ・元のWordファイルと同じフォルダに保存
;   ・元ファイルと同じ名前でPDF化
;   ・同名PDFがあれば自動上書き
;   ・複数ファイルの一括変換に対応
;   ・Wordは画面に表示しない
;   ・Wordの一時ファイル~$~)は除外
;   ・変換に失敗しても既存PDFは削除しない
;   ・Explorer上でのみF8を使用
; ============================================================


; ------------------------------------------------------------
; Explorer上でのみF8を有効化
; ------------------------------------------------------------
#HotIf WinActive("ahk_class CabinetWClass")
F8::ConvertSelectedWordToPDF()
#HotIf


; ============================================================
; 選択したWordファイルをPDFへ変換
; ============================================================
ConvertSelectedWordToPDF() {

    files := GetSelectedExplorerFiles()

    if (files.Length = 0) {
        ShowNotice("ファイルが選択されていません")
        return
    }


    ; --------------------------------------------------------
    ; Wordファイルだけ抽出
    ; --------------------------------------------------------
    wordFiles := []

    for filePath in files {

        SplitPath(filePath, &fileName, , &ext)

        ext := StrLower(ext)

        if (ext = "docx" || ext = "doc") {

            ; Wordが作成する一時ファイル~$~)を除外
            if (SubStr(fileName, 1, 2) != "~$")
                wordFiles.Push(filePath)
        }
    }


    if (wordFiles.Length = 0) {
        ShowNotice("Wordファイルを選択してください")
        return
    }


    ; --------------------------------------------------------
    ; Wordをバックグラウンド起動
    ; --------------------------------------------------------
    word := ""
    successCount := 0
    errors := []

    try {

        word := ComObject("Word.Application")

        word.Visible := false
        word.DisplayAlerts := 0
        word.ScreenUpdating := false


        ; ----------------------------------------------------
        ; ファイルごとにPDF化
        ; ----------------------------------------------------
        for filePath in wordFiles {

            doc := ""
            tmpPath := ""

            try {

                SplitPath(
                    filePath,
                    &fileName,
                    &dir,
                    &ext,
                    &nameNoExt
                )

                pdfPath := dir "\" nameNoExt ".pdf"

                ; まず一時PDFを作成す
                ; → PDF生成に失敗しても既存PDFを残すため
                tmpPath := dir "\~tmp_" nameNoExt "_" A_TickCount ".pdf"


                ; 念のため同名一時ファイルがあれば削除
                if FileExist(tmpPath)
                    FileDelete(tmpPath)


                ; Wordファイルを読み取り専用で開く
                ; Documents.Open(
                ;   FileName,
                ;   ConfirmConversions := false,
                ;   ReadOnly := true
                ; )
                doc := word.Documents.Open(
                    filePath,
                    false,
                    true
                )


                ; 17 = wdExportFormatPDF
                doc.ExportAsFixedFormat(
                    tmpPath,
                    17
                )


                ; Word文書を閉じる
                doc.Close(false)
                doc := ""


                ; PDFが正常に作られたことを確認
                if !FileExist(tmpPath)
                    throw Error("PDFファイルが生成されませんでした。")


                ; 一時PDF正式なPDF名へ
                ; true = 同名PDFがあれば上書き
                FileMove(
                    tmpPath,
                    pdfPath,
                    true
                )

                tmpPath := ""

                successCount++
            }
            catch Error as err {

                ; 開いているWord文書があれば閉じる
                if IsObject(doc) {
                    try doc.Close(false)
                }

                ; 一時PDFが残っていれば削除
                if (tmpPath != "" && FileExist(tmpPath)) {
                    try FileDelete(tmpPath)
                }

                SplitPath(filePath, &errorFileName)

                errors.Push(
                    errorFileName ":" err.Message
                )
            }
        }
    }
    catch Error as err {

        MsgBox(
            "Wordの起動またはPDF変換に失敗しました。`n`n"
            . err.Message,
            "PDF変換エラー",
            "Iconx"
        )
    }
    finally {

        ; ----------------------------------------------------
        ; Wordを確実に終了
        ; ----------------------------------------------------
        if IsObject(word) {
            try word.Quit()
        }
    }


    ; --------------------------------------------------------
    ; 結果表示
    ; --------------------------------------------------------
    if (errors.Length > 0) {

        message :=
            "PDF化完了:" successCount "件`n"
            . "エラー:" errors.Length "件`n`n"

        for errorText in errors
            message .= errorText "`n"

        MsgBox(
            message,
            "PDF変換結果",
            "Icon!"
        )

    } else if (successCount > 0) {

        ShowNotice(
            "PDF化完了:" successCount "件"
        )
    }
}


; ============================================================
; Explorerで現在選択されているファイルを取得
; ============================================================
GetSelectedExplorerFiles() {

    selectedFiles := []

    hwnd := WinExist("A")

    try {

        shell := ComObject("Shell.Application")

        for window in shell.Windows {

            try {

                if (window.HWND = hwnd) {

                    items := window.Document.SelectedItems

                    for item in items
                        selectedFiles.Push(item.Path)

                    break
                }
            }
        }
    }

    return selectedFiles
}


; ============================================================
; 簡易通知
; ============================================================
ShowNotice(message) {

    ToolTip(message)

    SetTimer(
        () => ToolTip(),
        -1500
    )
}

関連記事