banner
andrewji8

Being towards death

Heed not to the tree-rustling and leaf-lashing rain, Why not stroll along, whistle and sing under its rein. Lighter and better suited than horses are straw sandals and a bamboo staff, Who's afraid? A palm-leaf plaited cape provides enough to misty weather in life sustain. A thorny spring breeze sobers up the spirit, I feel a slight chill, The setting sun over the mountain offers greetings still. Looking back over the bleak passage survived, The return in time Shall not be affected by windswept rain or shine.
telegram
twitter
github

【Python自動化辦公】批量將world文檔轉為PDF,並統計頁碼

哈喽大家好,今天我們來展示一下,如何使用 Python 批量將 world 文檔轉變為 PDF 格式。

話不多說,直接開整!

pypdf2 是一個 Python 模塊,可以用來讀取、寫入和操作 PDF 文件。要安裝 pypdf2 模塊,請按照以下步驟操作:

確保你已經安裝了 Python。你可以在終端或命令提示符中輸入 python --version 來檢查 Python 是否已安裝。

pypdf2 模塊的安裝:
ModuleNotFoundError: No module named ‘PyPDF2’

image

安裝完成後,你可以在 Python 中使用 pypdf2 模塊來讀取、寫入和操作 PDF 文件。

例如,要讀取一個 PDF 文件中的文本內容,你可以在 Python 腳本中導入 pypdf2 模塊,然後使用 PdfFileReader 類讀取文件並遍歷每個頁面。下面是一個簡單的示例代碼:

import pypdf2  
  
pdf_file = pypdf2.PdfFileReader('example.pdf')  
for page_num in range(pdf_file.getNumPages()):  
    page = pdf_file.getPage(page_num)  
    print(page.extractText())

這將打印出 PDF 文件中的每個頁面的文本內容。

注意:
因 PyPDF2 版本更新原因,一些類和函數已經過時,想要採用替代函數,例如獲取 pdf 頁數 getNumPages 替換為直接使用 len (reader.pages)。

下面是兩個報錯的提示,把函數替換掉就行

PyPDF2.errors.DeprecationError: PdfFileReader is deprecated and was removed in PyPDF2 3.0.0. Use PdfReader instead.

PyPDF2.errors.DeprecationError: reader.getNumPages is deprecated and was removed in PyPDF2 3.0.0. Use len(reader.pages) instead.

image
利用 Python 代碼實現批量 word 文檔轉換成 PDF 格式
並對轉換的文檔,進行頁碼統計,如下(代碼示例)

# -*- coding:utf-8 -*-
import os  # 導入系統功能模塊
from win32com.client import Dispatch, DispatchEx  # 導入pywin32模塊的client包下的函數
from win32com.client import constants  #  導入pywin32模塊的client包下的保存COM常量的類
from win32com.client import gencache    #  導入pywin32模塊的client包下的gencache函數
from PyPDF2 import  PdfReader  # 獲取頁碼用
import re  # 導入正則表達式模塊

import pythoncom  # 導入封裝了OLE自動化API的模塊,該模塊為pywin32的子模塊


'''獲取指定目錄下的文件
   filepath:要遍歷的目錄
   filelist_out:輸出文件列表
   file_ext:文件的擴展名,默認為任何類型的文件
'''
def getfilenames(filepath='',filelist_out=[],file_ext='all'):
    # 遍歷filepath下的所有文件,包括子目錄下的文件
    for fpath, dirs, fs in os.walk(filepath):
        for f in fs:
            fi_d = os.path.join(fpath, f)
            if file_ext == '.doc':  # 遍歷Word文檔文件
                if os.path.splitext(fi_d)[1] in ['.doc','.docx']:   # 判斷是否為Word文件
                    filelist_out.append(re.sub(r'\\','/',fi_d))  # 添加到路徑列表中
            else:
                if  file_ext == 'all':  # 要獲取所有文件的情況
                    filelist_out.append(fi_d)  # 將文件路徑添加到路徑列表中
                elif os.path.splitext(fi_d)[1] == file_ext:  # 要獲取除了Wrod文件以外的文件
                    filelist_out.append(fi_d)  # 將文件路徑添加到路徑列表中
                else:
                    pass
        filelist_out.sort()  # 對路徑進行排序
    return filelist_out  # 返回文件完整路徑列表

# Word轉換為PDF(多個文件)
def wordtopdf(filelist,targetpath):
    totalPages = 0   # 記錄總頁碼
    valueList = []
    try:
        pythoncom.CoInitialize()   # 調用線程初始化COM庫,解決調用Word 2007時出現“尚未調用CoInitialize”錯誤的問題
        gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
        # 開始轉換
        w = Dispatch("Word.Application")
        for fullfilename in filelist:
            (filepath,filename) = os.path.split(fullfilename)  # 分割文件路徑和文件名,其中,filepath表示文件路徑;filename表示文件名
            softfilename = os.path.splitext(filename)  # 分割文件名和擴展名
            os.chdir(filepath)  
            doc = os.path.abspath(filename)
            os.chdir(targetpath)
            pdfname = softfilename[0] + ".pdf"
            output = os.path.abspath(pdfname)
            pdf_name = output

            # 文檔路徑需要為絕對路徑,因為Word啟動後當前路徑不是調用腳本時的當前路徑。
            try: # 捕捉異常
                doc = w.Documents.Open(doc, ReadOnly=1)
                doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF, \
                                        Item=constants.wdExportDocumentWithMarkup,
                                        CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
            except Exception as e: # 處理異常
                print(e)
            if os.path.isfile(pdf_name): # 判斷文件是否存在
                # 獲取頁碼
                pages = getPdfPageNum(pdf_name)   # 獲取頁碼
                valueList.append([fullfilename,str(pages)])
                totalPages += pages  # 累加頁碼
                # os.remove(pdf_name)  # 刪除生成的PDF文件
            else:
                print('轉換失敗!')
                return False
        w.Quit(constants.wdDoNotSaveChanges) # 退出Word應用程序
        return totalPages,valueList  # 返回總頁碼和每個文檔的頁碼
    except TypeError as e:
        print('出錯了!')
        print(e)
        return False
'''
功能:統計文檔頁碼
path:文件絕對路徑
'''
def getPdfPageNum(path):
    with open(path, "rb") as file:
        doc = PdfReader(file)
        pagecount = len(doc.pages)
    return pagecount

if __name__ == '__main__':
    sourcepath = r"C:/Users/Lenovo/Desktop/python代碼示例/word/"  # 指定源路徑(Word文檔所在路徑)
    targetpath = r"C:/Users/Lenovo/Desktop/python代碼示例/pdf/"  # 指定目標路徑(PDF保存路徑)
    filelist = getfilenames(sourcepath,[],'.doc')  # 獲取Word文檔路徑
    valueList = wordtopdf(filelist,targetpath)  # 實現將Word文檔批量轉換為PDF
    resultList = valueList[1]  # 獲取統計結果
    if valueList:
        for i in resultList:
            print(i[0],i[1])
        totalPages = str(valueList[0]) # 總頁數
        print("合計頁數:",totalPages)
    else:
        print("沒有要統計的文件或者統計失敗!")

image

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。