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

时间:2019-10-29 07:00:41

标签: python macos pypdf2

我想做什么

-我想颠倒大约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的新手,对不起。

2 个答案:

答案 0 :(得分:1)

即使页面最初来自不同的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)
...

答案 1 :(得分:0)

这似乎是一个缩进问题。您的保存指令缩进到内部循环,而不是最外层的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)