AHK - 将 DOCX 批量转换为 PDF

参考资料

功能说明

  1. 使用 COM 物件 Word.Application,将 DOCX 档转换为 PDF 格式
  2. 整批转换资料夹里的所有 DOCX 档
  3. 使用 ExportAsFixedFormat 方法

程序源代码请参见:https://gist.github.com/emisjerry/5f936143f1086cc4b0eb100e891dbed3

我们要做的修改只要将第三行的存放 docx 的文件夹路径设定一下就好,注意只能对 docx 进行转换,无法转换 doc 文档

通过与 docx 自带的 PDF 转换比较了一下,生成的 PDF 大小一模一样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
;; 将DOCX批量转换为PDF

sFolder := "Z:\DOC"
sOutputExt := ".pdf"

Loop %sFolder%\*.docx {
sInputFilename = %A_LoopFileName%
;MsgBox filename=%sPdfFileName%
iPos := InStr(sInputFilename, "~")
if (iPos = 1) {
Continue
}
Docx2Pdf(sFolder . "\" . sInputFilename, sOutputExt)
}

Docx2Pdf(sInputFilename, sOutputExt) {
WD := ComObjCreate("Word.Application") ; Create Word object
WD.Documents.Open(sInputFilename) ;open this file
WD.visible:=0 ;make visible for this example. Normally set to zero
iFormat := 17
sOutputFilename := StrReplace(sInputFilename, ".docx", ".pdf")
;MsgBox fn=%sOutputFilename%, ext=%sOutputExt%, format=%iFormat%
;;WdSaveFormat https://docs.microsoft.com/zh-tw/office/vba/api/word.wdsaveformat

OpenAfterExport := True
OptimizeFor := False
Range := 0
From := 1
To := False
/*
Item:= 0
IncludeDocProps := False
KeepIRM := True
reateBookmarks := wdExportCreateHeadingBookmarks := 1
ocStructureTags := False
BitmapMissingFonts := True
UseISO19005_1 := False
*/

;; WD.ActiveDocument.ExportAsFixedFormat(sOutputFilename, 17, OpenAfterExport, OptimizeFor, Range, From, To, Item, IncludeDocProps, KeepIRM, CreateBookmarks, DocStructureTags, BitmapMissingFonts, UseISO19005_1)

WD.ActiveDocument.ExportAsFixedFormat(sOutputFilename,17,OpenAfterExport,OptimizeFor,Range,From,To)

WD.quit ; quit Word
WD := ""
}