Python 如何實現合併 PDF 文件?

在處理多個 PDF 文檔時,頻繁地打開關閉文件會嚴重影響效率。因此,對於一大堆內容相關的 PDF 文件,我們可以先將這些 PDF 文件合併起來再操作,從而提高工作效率。比如,在傳送大量的 PDF 文檔時,在處理同一項目下的多個 PDF 文檔時,或在打印一系列 PDF 文檔時,將文檔合併起來可以減少工作量。本文將分享3種使用 Python 合併 PDF 文件的實現方法。

 

安裝:

Python中合併PDF需要用到 Spire.PDF for Python 庫。 安裝十分簡單,直接使用以下pip命令即可。或者可以下載後再安裝。

pip install Spire.PDF

 

方法1:通過 MergeFiles () 直接合並 PDF 文件

MergeFiles(List[str]) 方法可以將一個文件路徑列表對應的所有 PDF 文件按列表順序合併爲一個 PDF 文件。代碼如下:

from spire.pdf.common import *
from spire.pdf import *
import os

# 指定文件夾路徑
folder_path = "G:/文檔/"

# 遍歷文件夾中的文件並創建文件路徑列表
pdf_files = []
for file_name in sorted(os.listdir(folder_path)):
    if file_name.endswith(".pdf"):
        file_path = os.path.join(folder_path, file_name)
        pdf_files.append(file_path)

# 合併PDF文檔
pdf = PdfDocument.MergeFiles(pdf_files)

# 保存結果文檔
pdf.Save("output/合併PDF.pdf", FileFormat.PDF)
pdf.Close()

 

方法2:通過AppendPage() 插入頁面合併 PDF 文件

AppendPage(PdfDocument) 方法可以在一個 PDF 文件中插入另一個 PDF 文件的所有頁面。 具體實現代碼參考:

from spire.pdf.common import *
from spire.pdf import *

# 遍歷文件夾中的文件,載入每個PDF文件PdfDocument對象並列表
folder_path = "G:/文檔/"
pdf_files = []
for file_name in sorted(os.listdir(folder_path)):
    if file_name.endswith(".pdf"):
        file_path = os.path.join(folder_path, file_name)
        pdf_files.append(PdfDocument(file_path))

# 創建一個PdfDocument對象
newPdf = PdfDocument()

# 將加載的PDF文檔的頁面插入到新的PDF文檔中
for pdf in pdf_files:
    newPdf.AppendPage(pdf)

# 保存新的PDF文檔
newPdf.SaveToFile("output/插入頁面合併PDF.pdf")

 

方法3:合併不同 PDF 文件的指定頁面

InsertPage (PdfDocument, pageIndex: int) 方法可以將一個 PDF 文件的指定頁面插入到另一個 PDF 文件中。我們可以通過這個方法合併不同 PDF 文件的指定頁面。

from spire.pdf import *
from spire.pdf.common import *

# 創建PDF文件路徑列表
file1 = "示例1.pdf"
file2 = "示例2.pdf"
file3 = "示例3.pdf"
files = [file1, file2, file3]

# 加載每個PDF文件並添加到列表中
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# 創建一個PdfDocument對象
newPdf = PdfDocument()

# 將加載的PDF文檔中選擇的頁面插入到新文檔中
newPdf.InsertPage(pdfs[0], 0)
newPdf.InsertPage(pdfs[1], 1)
newPdf.InsertPageRange(pdfs[2], 0, 1)

# 保存新的PDF文檔
newPdf.SaveToFile("output/合併不同PDF的指定頁面.pdf")

 

以上就是關於如何使用 Spire.PDF for Python 合併 PDF 文件的操作介紹。大家可自行測試,如有問題歡迎反饋討論。

如果想了解更多此第三方Python庫的功能,可前往 Spire.PDF for Python 中文教程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章