python合并多个pdf文件

Python实现多个PDF文件合并
部署运行你感兴趣的模型镜像

python合并多个pdf文件

假设您有个无聊的工作,将几十个PDF文档合并成一个PDF文件。 他们每个都有封面页作为第一页,但你不希望在最终结果中重复覆盖表。 即使有有很多免费的程序来组合PDF,其中许多只是合并整个文件在一起。 让我们编写一个Python程序来自定义哪些页面你想要的是组合PDF。从高层次来看,这是程序将要做的事情:

  • 查找当前工作目录中的所有PDF文件。
  • 对文件名进行排序,以便按顺序添加PDF。
  • 将每个PDF的每个页面(不包括第一页)写入输出文件。
    在实现方面,您的代码需要执行以下操作:
  • 调用 os.listdir() 来查找工作目录中的所有文件,删除所有非PDF文件。
  • 调用Python的sort()列表方法来按字母顺序排列文件名。
  • 为输出PDF创建PdfFileWriter对象。
  • 遍历每个PDF文件,为其创建PdfFileReader对象。
  • 在每个PDF文件中循环遍历每个页面(第一页除外)。
  • 将页面添加到输出PDF。
  • 将输出PDF写入名为allminutes.pdf的文件。
    对于此项目,请打开一个新的文件编辑器窗口并将其另存为 “combinePdfs.py
Step 1:找到所有的PDF文件

首先,您的程序需要获取所有扩展名为.pdf的文件的列表
当前的工作目录并对它们进行排序。 让你的代码看起来像
以下:

在这里插入代码片

在shebang线和关于什么的描述性评论之后程序没有,这段代码导入了os和PyPDF2模块。该
os.listdir(’.’) 调用将返回当前工作中的每个文件的列表目录。 代码循环遍历此列表,并仅添加带有.pdf扩展的那些文件pdfFiles。之后,此列表按字母顺序排序,使用key = str.lower关键字参数对sort() 进行排序。创建PdfFileWriter对象以保存组合的PDF页面。最后,一些评论概述了该计划的其余部分。

#! /usr/bin/python3
# combinePdfs.py - Combines all the PDFs in the current working directory into
# a single PDF.

import PyPDF2, os

# Get all the PDF filenames.
pdfFiles = []
for filename in os.listdir('.'):
    if filename.endswith('.pdf'):
        pdfFiles.append(filename)
pdfFiles.sort(key = str.lower)

pdfWriter = PyPDF2.PdfFileWriter()

# TODO: Loop through all the PDF files.

# TODO: Loop through all the pages (except the first) and add them.

# TODO: Save the resulting PDF to a file.

第二步:打开每一个 PDF 文件

现在程序必须读取pdfFiles中的每个PDF文件。 添加以下内容:

#! /usr/bin/python3
# combinePdfs.py - Combines all the PDFs in the current working directory into
# a single PDF.

import PyPDF2, os

# Get all the PDF filenames.
pdfFiles = []
for filename in os.listdir('.'):
    if filename.endswith('.pdf'):
        pdfFiles.append(filename)
pdfFiles.sort(key = str.lower)

pdfWriter = PyPDF2.PdfFileWriter()

# Loop through all the PDF files.
for filename in pdfFiles:
    pdfFileObj = open(filename, 'rb')
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
    # TODO: Loop through all the pages (except the first) and add them.

# TODO: Save the resulting PDF to a file.

对于每个PDF,循环通过以读二进制模式(以’rb’作为第二个参数)调用open() 。 open()调用返回一个File对象,它被传递给PyPDF2.PdfFileReader() 。

第三步: 添加每一页

对于每个PDF,您都希望遍历除第一个页面之外的每个页面。 加上这个代码到你的程序:

#! /usr/bin/python3
# combinePdfs.py - Combines all the PDFs in the current working directory into
# a single PDF.

import PyPDF2, os

# Get all the PDF filenames.
pdfFiles = []
for filename in os.listdir('.'):
    if filename.endswith('.pdf'):
        pdfFiles.append(filename)
pdfFiles.sort(key = str.lower)

pdfWriter = PyPDF2.PdfFileWriter()

# Loop through all the PDF files.
for filename in pdfFiles:
    pdfFileObj = open(filename, 'rb')
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
    # Loop through all the pages (except the first) and add them.
    for pageNum in range(1, pdfReader.numPages):
        pageObj = pdfReader.getPage(pageNum)
        pdfWriter.addPage(pageObj)



# TODO: Save the resulting PDF to a file.

for循环中的代码将每个Page对象分别复制到PdfFileWriter对象。 请记住,您想跳过第一页。 以来
PyPDF2认为0是第一页,你的循环应该从1 开始,然后转到但不包括pdfReader.numPages中的整数。

第四步: 保存结果

在这些嵌套的for循环完成循环之后,pdfWriter变量将会循环包含PdfFileWriter对象,其中包含所有PDF的页面。最后一步是将此内容写入硬盘驱动器上的文件。 将此代码添加到你程序中:

#!/usr/bin/python3
# combinePdfs.py - Combines all the PDFs in the current working directory into
# a single PDF.

import PyPDF2, os

# Get all the PDF filenames.
pdfFiles = []
for filename in os.listdir('/home/hux/books/python'):
    if filename.endswith('.pdf'):
        pdfFiles.append('/home/hux/books/python/'+filename)
pdfFiles.sort(key = str.lower)

pdfWriter = PyPDF2.PdfFileWriter()

# Loop through all the PDF files.
for filename in pdfFiles:
    pdfFileObj = open(filename, 'rb')
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj, strict=False)
    for pageNum in range(1, pdfReader.numPages):
        pageObj = pdfReader.getPage(pageNum)
        pdfWriter.addPage(pageObj)

pdfOutput = open('allminutes.pdf', 'wb')
pdfWriter.write(pdfOutput)
pdfOutput.close()

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

### 回答1: 你可以使用 PyPDF2 库来合并多个 PDF 文件为一个 PDF 文件。首先,你需要安装这个库,使用以下命令: ```python pip install pypdf2 ``` 然后,你可以使用以下代码来合并多个 PDF 文件: ```python import os import glob import PyPDF2 # 创建一个 PDF 合并器 merger = PyPDF2.PdfFileMerger() # 读取当前目录下的所有 PDF 文件 for pdf in glob.glob("*.pdf"): # 读取每个 PDF 文件 with open(pdf, "rb") as f: merger.append(f) # 将所有 PDF 文件合并到一个新的 PDF 文件中 with open("merged.pdf", "wb") as f: merger.write(f) ``` 这段代码会将当前目录下的所有 PDF 文件合并为一个新的 PDF 文件,命名为 "merged.pdf"。 希望这对你有帮助! ### 回答2: 要合并多个PDF文件为一个PDF文件,可以使用Python的PyPDF2库来实现。 首先,你需要安装PyPDF2库,可以使用以下命令来安装: ``` pip install PyPDF2 ``` 接下来,你可以使用以下代码来合并多个PDF文件为一个PDF文件: ```python import PyPDF2 def merge_pdf(input_paths, output_path): merger = PyPDF2.PdfFileMerger() for path in input_paths: with open(path, 'rb') as file: merger.append(file) with open(output_path, 'wb') as file: merger.write(file) if __name__ == '__main__': input_paths = ['file1.pdf', 'file2.pdf', 'file3.pdf'] # 待合并PDF文件路径列表 output_path = 'merged.pdf' # 合并后的PDF文件路径 merge_pdf(input_paths, output_path) ``` 在上述代码中,首先导入PyPDF2库。然后定义了一个名为`merge_pdf`的函数,接收两个参数:`input_paths`和`output_path`。`input_paths`是待合并PDF文件路径列表,`output_path`是合并后的PDF文件路径。 在`merge_pdf`函数中,创建了一个`PdfFileMerger`对象用于合并PDF文件。然后,通过遍历`input_paths`列表,打开每一个PDF文件,并使用`append`方法将其添加到合并对象中。 最后,使用`wb`模式打开输出路径的文件,并使用`write`方法将合并对象的内容写入文件。 使用上述代码,你可以将多个PDF文件合并为一个PDF文件,并保存为指定路径。 ### 回答3: 要使用Python合并多个pdf文件为一个pdf文件,你可以使用PyPDF2库。以下是一个简单的代码示例: ```python from PyPDF2 import PdfMerger # 定义要合并pdf文件列表 pdf_files = ['file1.pdf', 'file2.pdf', 'file3.pdf'] # 创建PdfMerger对象 merger = PdfMerger() # 逐个合并pdf文件 for pdf_file in pdf_files: merger.append(pdf_file) # 定义目标合并后的pdf文件名 output_file = 'merged_file.pdf' # 将合并后的pdf文件保存到目标文件中 merger.write(output_file) # 关闭PdfMerger对象 merger.close() print('pdf文件合并完成!') ``` 在代码中,我们首先导入了`PdfMerger`类。然后,我们定义了要合并pdf文件列表,并创建了一个`PdfMerger`对象`merger`。 接着,我们使用`append()`方法逐个将pdf文件添加到`merger`对象中。 然后,我们定义了合并后的pdf文件名`output_file`,并通过`write()`方法将合并后的pdf文件保存到目标文件中。 最后,我们关闭了`merger`对象,并输出了合并完成的提示信息。 希望以上代码能够帮助你实现合并多个pdf文件为一个pdf文件的需求!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值