2020年5月21日 星期四

Windows MS word檔批次轉pdf工具

不知道大家有沒有想要一次轉換好幾個word檔成pdf檔的經驗呢?
雖然有很不少線上工具可以用
而且有些 word 本身也有支援轉檔的功能
可是一個一個檔案來操作實在是太累了
今天下午在處理這件事的時候,就順手把
python 原始碼打包成執行檔了

原始碼與執行檔案連結跟大家分享:
https://drive.google.com/drive/folders/1SRHodqTzwkxZu_SRtTeCCRdhCDbYrQQB?usp=sharing



#coding:utf8
import os, sys
from imp import reload
reload(sys)
from win32com.client import Dispatch, constants, gencache
def doc2pdf(sourceF,tartgetF):
    #sourceF = 'D:\\1.doc'
    #tartgetF = 'D:\\1.pdf'
    print(sourceF,' ==> ',tartgetF)
    # enable python COM support for Word 2007
    # this is generated by: makepy.py -i "Microsoft Word 12.0 Object Library"
    gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
    # 開始轉換
    w = Dispatch("Word.Application")
    try:
        doc = w.Documents.Open(sourceF, ReadOnly=1)
        doc.ExportAsFixedFormat(tartgetF, constants.wdExportFormatPDF, \
        Item=constants.wdExportDocumentWithMarkup,
        CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
    except: print('exception')
    finally: w.Quit(constants.wdDoNotSaveChanges)
    if os.path.isfile(tartgetF):print('translate success')
    else:print('translate fail')
    
desktop = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') 
print('DOC/DOCX  to PDF  batch converter .  by K.Y. Lee (c) 2020 All Rights Reserved')
folder = input('„enter the target folder of MS doc/docx files on YOUR Desktop\n輸入欲轉換之word文件資料夾名稱(桌面上)[不需完整路徑]:')
DIR = desktop+'\\'+folder+"\\"

files = os.listdir(DIR)

for f in files:
    ii = f.find('.doc')
    if ii>0:
        doc2pdf(DIR+f,DIR+f[:ii]+'.pdf')