需求背景:
由於要列印幾十頁pdf,跟列印店對接的時候,為了防止被坑,提前瞭解一下,所有文件一共有多少頁,於是想到了用python來提取pdf檔案的頁數
完整程式碼:
import os from PyPDF2 import PdfReader def get_pdf_page_count(folder_path): # 初始化總頁數變數 total_pages = 0 # 獲取資料夾中所有PDF檔案的路徑 pdf_files = [f for f in os.listdir(folder_path) if f.endswith('.pdf')] # 遍歷每個PDF檔案並獲取頁數 for pdf_file in pdf_files: file_path = os.path.join(folder_path, pdf_file) with open(file_path, 'rb') as f: pdf_reader = PdfReader(f) page_count = len(pdf_reader.pages) total_pages += page_count # 累加頁數 print(f"{pdf_file}: {page_count} 頁") # 返回總頁數 return total_pages # 指定資料夾路徑 folder_path = "E:\\xxx\\可列印版本-PPT-黑白版" # 替換為您的PDF資料夾路徑 # 獲取PDF檔案的頁數 total_pages_in_folder = get_pdf_page_count(folder_path) print(f"資料夾中所有PDF檔案的總頁數為: {total_pages_in_folder} 頁")