1. 程式人生 > >[Python Study Notes]批量將wold轉換為pdf

[Python Study Notes]批量將wold轉換為pdf

creat turn != file get dir files lose documents

本文代碼,由原ppt2pdf.py進行改寫

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘
>>文件: word2pdf.py
>>作者: liu yang
>>郵箱: [email protected]
>>博客: www.cnblogs.com/liu66blog

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os
# 調用com組件包
import comtypes.client

def init_word():
    word = comtypes.client.CreateObject("Word.Application")
    word.Visible = 1
    return word

# 第二步:找到該路徑下的所有doc(x)文件,並將其路徑添加到cwd
def convert_files_in_folder(word, folder):
    # 將當前所有文件及文件夾添加進列表
    files = os.listdir(folder)
    # print(‘files:‘,files)
    # 將所有以.doc(x)結尾的文件加入cwd path
    pptfiles = [f for f in files if f.endswith((".doc", ".docx"))]
    for pptfile in pptfiles:
        # 加入判斷,如果當前轉換成的pdf已存在,就跳過不添加
        print(pptfile)
        if pptfile+‘.pdf‘ in files :
            break
        # 加入cwd環境
        fullpath = os.path.join(cwd, pptfile)
        ppt_to_pdf(word, fullpath, fullpath)

#第三步:將cwd路徑下轉換成pdf格式
def ppt_to_pdf(word, inputFileName, outputFileName, formatType = 17):
    # 切片取後綴是否為pdf
    if outputFileName[-3:] != ‘pdf‘:
        outputFileName = outputFileName + ".pdf"
    # 調用接口進行轉換
    print(inputFileName)
    deck = word.Documents.Open(inputFileName)
    deck.SaveAs(outputFileName, formatType) # formatType = 17 for word to pdf
    deck.Close()

if __name__ == "__main__":
    # 創建Word應用
    word = init_word()
    # 得到當前路徑
    cwd = os.getcwd()
    # 打印當前路徑
    print(cwd)
    # 調用Word進行轉換cwd path下的doc(x)格式
    convert_files_in_folder(word, cwd)
    # 轉換結束後關閉
    word.Quit()

[Python Study Notes]批量將wold轉換為pdf