簡體   English   中英

如何使用pyPDF2反轉多個PDF文件的多個順序?

[英]How do I reverse multiple the order of multiple PDF files with pyPDF2?

我想做的事

-我想顛倒大約 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 很陌生,對不起。

您不斷將頁面添加到相同的 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)
...

這似乎是一個縮進問題。 您的保存指令縮進到內部循環而不是最外面的 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM