Skip to main content
 首页 » 编程设计

python之如何使用 pyPDF2 反转多个 PDF 文件的顺序

2024年11月01日7lautakyan007

我想做什么

-我想颠倒大约 10 个 PDF 的顺序。

我做了什么

-我在这里找到了一个非常好的方法。 (非常感谢这篇文章): How do I reverse the order of the pages in a pdf file using pyPdf?
-但是这段代码只为一个文件编写。
-所以我将代码编辑为如下所示。

我的代码

from PyPDF2 import PdfFileWriter, PdfFileReader 
import tkinter as tk 
from tkinter import filedialog 
import ntpath 
import os 
import glob 
 
 
output_pdf = PdfFileWriter() 
 
# grab the location of the file path sent 
def path_leaf(path): 
    head, tail = ntpath.split(path) 
    return head 
 
# graphical file selection 
def grab_file_path(): 
    # use dialog to select file 
    file_dialog_window = tk.Tk() 
    file_dialog_window.withdraw()  # hides the tk.TK() window 
    # use dialog to select file 
    grabbed_file_path = filedialog.askopenfilenames() 
    return grabbed_file_path 
 
 
# file to be reversed 
filePaths = grab_file_path() 
 
# open file and read 
for filePath in filePaths: 
    with open(filePath, 'rb') as readfile: 
        input_pdf = PdfFileReader(readfile) 
 
        # reverse order one page at time 
        for page in reversed(input_pdf.pages): 
            output_pdf.addPage(page) 
 
        # graphical way to get where to select file starting at input file location 
        dirOfFileToBeSaved = os.path.join(path_leaf(filePath), 'reverse' + os.path.basename(filePath))  
        # write the file created 
        with open(dirOfFileToBeSaved, "wb") as writefile: 
            output_pdf.write(writefile) 

问题

-它确实颠倒了顺序。
-但它不仅颠倒了顺序,还合并了所有文件。
-例如

A.pdf: page c, b, a     
B.pdf: page f, e, d   
C.pdf: page i, h, g   

结果是这样的

reverseA.pdf: page a, b, c   
reverseB.pdf: page a, b, c, d, e, f   
reverseC.pdf: page a, b, c, d, e, f, g, h, i   

我的问题

-我应该如何编辑此代码以使文件不会被合并?
-我是 python 的新手,抱歉。

请您参考如下方法:

您不断向同一个 output_pdf 添加页面,即使这些页面最初来自不同的 PDF。您可以通过添加来解决这个问题

output_pdf = PdfFileWriter() 

在开始一个新文件之前。你会得到:

... 
# open file and read 
for filePath in filePaths: 
    output_pdf = PdfFileWriter() 
    with open(filePath, 'rb') as readfile: 
        input_pdf = PdfFileReader(readfile) 
...