python - 如何使用 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很陌生,对不起。
解决方案
您不断将页面添加到相同的 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)
...
推荐阅读
- c++ - 从公共类与私有类 C++ 继承
- vba - Word表格中的相互排除复选框
- karate - 使用空手道的故事书 UI 中的 iframe 元素不可交互
- sql - 在 SQL Server 中的两个数字列之间选择行
- shibboleth - Shibboleth 4 IDP:将属性解析器分配给特定流
- android - 如何在 Android 的 Renderscript 中释放内存?
- c - 语法困难,意外输出
- docusignapi - DocuSign:一个帐户的多个基本 URI?
- android - android adb在没有连接HDMI显示器的情况下重启后连接失败
- javascript - 发送多个图像(Discord JS)