最近遇到一個問題,想要對四個不同的PDF,分別擷取1~2頁、3~4頁、5~6頁、7~8頁,合併成一個總共8頁的PDF。那該怎麼寫程式來處理這件事呢?那如果是用線上拆分PDF網頁與線上合併PDF網頁,該怎麼做呢?則是需要將四個不同PDF分別上傳到拆分網頁後再一頁一頁的PDF下載下來,再將所需要頁數的PDF放在同一個資料夾,然後再上傳到合併網頁,最後下到自己的資料夾。不斷地上傳、下載。光是處理這些步驟,所花的時間根本就無法想像。能不能有個程式,會掃描input資料夾內檔案。匯出input資料夾內所有檔案名稱,我們只要設定起始頁面與最後頁面。再對程式點兩下,就會合併所有的頁面到一個PDF。換句話說,只要點兩下兩次,就能依照設定拆分指定PDF頁數並合併成設定好的一個PDF。
下載檔案。解壓密碼:demo1234
Here is the website where you can download the program and find instructions:
Here is the website where you can download the program and find instructions:
Download。Extraction Password: demo1234
使用說明(Instructions for use):
1.下載後,解壓縮。解壓縮的方式要保持原有的資料夾架構,如下:
input 與 source 。如下圖:
2.將所需的PDF 放入資料夾input 內 3.滑鼠對pyPDFDivide.exe點兩下,就會產出一個OutputFileName.txt
4.在OutputFileName.txt,填寫所需的頁數起始範圍後,儲存。
5.滑鼠對pyPDFDivide.exe點兩下,就會產出output.pdf
6.該output.pdf即為所求。
使用教學(Instructional videos):
以下是開發過程與原始碼 (Development process and code):
安裝python套件 pikepdf:
pip install pikepdf
程式名稱(Program name):pyPDFDivide.py
程式內容(Code):
import os
from pikepdf import Pdf
# 取得目前的工作目錄
current_directory = os.getcwd()
# 取得目前的工作目錄內input資料夾的路徑
current_directory_input = current_directory + "\\input\\"
# 取得工作目錄input資料夾內所有檔案名稱
current_directory_input_files = os.listdir(current_directory_input)
# 檢查 OutputFileName.txt 是否存在
if os.path.exists(current_directory + "\\OutputFileName.txt"):
# 如果存在,則讀取檔案內容
with open("OutputFileName.txt", "r", encoding="utf-8") as file:
content = file.readlines()
else:
# 如果不存在,則創建 OutputFileName.txt 並寫入內容
with open("OutputFileName.txt", "w", encoding="utf-8") as file:
for current_directory_input_file in current_directory_input_files:
# 開啟每個 PDF 檔案
pdf = Pdf.open(current_directory_input + current_directory_input_file)
pages = pdf.pages # 獲取 PDF 檔案的頁面數量
# 寫入檔案名稱和頁面數量到 OutputFileName.txt
file.write("FileName:" + str(current_directory_input_file) + "\nTotalPages:" + str(len(pages)) + "\n" + "StartPage:\nEndPage:\n")
num = 0 # 計數器
FileNameList = [] # 存放檔案名稱的列表
StartPageList = [] # 存放起始頁面的列表
EndPageList = [] # 存放結束頁面的列表
# 解析 OutputFileName.txt 的內容
for i in content:
if num % 4 == 0:
# 每四行的第一行是檔案名稱
temp, tempfilename = i.split(':')
FileNameList.append(tempfilename.replace("\n", ""))
elif num % 4 == 2:
# 每四行的第三行是起始頁面
temp, tempstartpage = i.split(':')
StartPageList.append(tempstartpage.replace("\n", ""))
elif num % 4 == 3:
# 每四行的第四行是結束頁面
temp, tempendpage = i.split(':')
EndPageList.append(tempendpage.replace("\n", ""))
num = num + 1 # 增加計數器
# 將設定檔 OutputFileName.txt 的內容依序將指定 PDF 拆分合併到 output.pdf
output = Pdf.new() # 創建一個新的 PDF 檔案
for i in range(len(FileNameList)):
# 開啟每個指定的 PDF 檔案
pdf = Pdf.open(current_directory_input + FileNameList[i])
pages = pdf.pages # 獲取 PDF 檔案的頁面
a = int(StartPageList[i]) # 轉換起始頁面為整數
b = int(EndPageList[i]) # 轉換結束頁面為整數
# 從起始頁面到結束頁面將頁面添加到新的 PDF 檔案中
for j in range(a, b + 1):
output.pages.append(pages[j])
# 儲存合併後的 PDF 檔案
output.save("output.pdf")
沒有留言:
張貼留言