Python操作PDF:PDF文件合并与PDF页面重排

处理大量的 PDF 文档是非常麻烦的事情,频繁地打开关闭文件会严重影响工作效率。对于一大堆内容相关的 PDF 文件,我们在处理时可以将这些 PDF 文件合并起来,作为单一文件处理,从而提高处理效率。同时,我们也可以选取不同PDF文件中想要的页面制作新的 PDF 文件。本文将介绍如何利用 Python 合并 PDF 文件以及选取页面组成新的PDF文件。

文章目录

    • 通过 MergeFiles () 方法直接合并 PDF 文件
    • 通过插入页面合并 PDF 文档
    • 合并不同 PDF 文件的指定页面


使用工具:Spire.PDF for Python
PyPI:
pip install Spire.Doc


通过 MergeFiles () 方法直接合并 PDF 文件

MergeFiles(List[str]) 方法可以将一个文件路径列表对应的所有 PDF 文件按列表顺序合并为一个 PDF 文件。操作示例如下:

  1. 遍历文件夹,创建 PDF 文件路径的列表。
  2. 使用 PdfDocument.MergeFiles() 方法合并列表对应的 PDF 文件,得到一个 PdfDocumentBase 对象。
  3. 使用 PdfDocumentBase.Save() 方法保存合并结果。

Python

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()

通过插入页面合并 PDF 文档

AppendPage(PdfDocument) 方法可以在一个 PDF 文件中插入另一个 PDF 文件的所有页面,从而实现合并PDF文件。以下是通过这种方法合并 PDF 文件的操作示例:

  1. 载入文件夹下的 PDF 文件为 PdfDocument 对象并创建列表。
  2. 创建一个新的 PdfDocument 对象。
  3. PdfDocument.AppendPage(PdfDocument) 方法将载入的 PDF 文件的页面插入到新的 PDF 文件中。
  4. 使用 PdfDocument.SaveToFile() 方法保存新的 PDF 文件。

Python

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")

合并不同 PDF 文件的指定页面

InsertPage(PdfDocument, pageIndex: int) 方法可以将一个 PDF 文件的指定页面插入到另一个 PDF 文件中。我们可以通过这个方法合并不同 PDF 文件的指定页面。以下是操作示例:

  1. 创建 PDF 文件路径列表。
  2. 载入 PDF 文件为 PdfDocument 对象并创建列表。
  3. 创建新的 PdfDocument 对象。
  4. 使用 PdfDocument.InsertPage() 方法插入指定 PDF 文件的指定页面到新的 PDF 文件种。
  5. 使用 PdfDocument.SaveToFile() 方法保存新的 PDF 文件。

Python

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 Pytho 合并 PDF 文件的操作介绍。如果你想了解更多此 API 的功能,可前往 Spire.PDF for Python 中文教程了解。

你可能感兴趣的:(Python,PDF,python,pdf,windows,开发语言)