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



我想做什么

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

我所做的

-我在这里找到了一个很好的方法。(非常感谢这篇文章(:如何使用pyPdf反转pdf文件中页面的顺序
-但此代码仅为一个文件编写
-所以我将代码编辑为如下所示。

我的代码

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很陌生。

即使页面最初来自不同的pdf,您也会不断向同一个output_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)
...

这似乎是一个缩进问题。您的保存指令缩进到内部循环,而不是最外层的for循环。请尝试以下具有正确缩进的内容。

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

最新更新