假设一个文件有3张纸6页,A1 A2 B1 B2 C1 C2
使用打印机单面进纸器扫描正面,第一个文件包含页数分别为A1 B1 C1
然后把文件反过来扫描背面,此时文档顺序是反的。所以第二个文件包含的页数为 C2 B2 A2
用python处理PDF实现合并。
地址:https://pan.fanyaozu.com/s/JKJhX
码 隐藏代码
import PyPDF2
fileName1 = "f1.pdf"
fileName2 = "f2.pdf"
newFileName = "new.pdf"
with open(fileName1, 'rb') as f1, open(fileName2, 'rb') as f2, open(newFileName, "wb") as newf:
reader1 = PyPDF2.PdfFileReader(f1)
reader2 = PyPDF2.PdfFileReader(f2)
writer = PyPDF2.PdfFileWriter()
if reader1.numPages != reader2.numPages:
print('页数不相等')
exit(1)
for i in range(reader1.numPages):
writer.addPage(reader1.getPage(i))
writer.addPage(reader2.getPage(-(i + 1)))
writer.write(newf)
后续
后续
今天有个同事有十几份正反面文件要扫描,为了降低使用门槛,我更新了代码并且用pyinstaller
进行了封装
复制代码 隐藏代码
import os
import ntpath
import sys
import PyPDF2
def merge(file1, file2):
if not (file1.endswith(".pdf") and file2.endswith(".pdf")):
print('文件类型错误')
raise FileExistsError
if not (ntpath.exists(file1) and ntpath.exists(file2)):
print('文件不存在')
raise FileNotFoundError
with open(file1, 'rb') as f1, \
open(file2, 'rb') as f2, \
open(ntpath.dirname(file1) + "\\" + ntpath.splitext(ntpath.basename(file1))[0] + "+" + ntpath.splitext(
ntpath.basename(file2))[0] + ".pdf",
"wb") as newf:
reader1 = PyPDF2.PdfFileReader(f1)
reader2 = PyPDF2.PdfFileReader(f2)
writer = PyPDF2.PdfFileWriter()
if reader1.numPages != reader2.numPages:
print('页数不相等')
raise FileExistsError
for i in range(reader1.numPages):
writer.addPage(reader1.getPage(i))
writer.addPage(reader2.getPage(-(i + 1)))
writer.write(newf)
def print_help():
help_str = '''
帮助信息:
可双击打开后手动输入路径
也可以把要合并的文件路径以参数形式传入(数量必须为偶数)
合并是以文件名排序的
'''
print(help_str)
def main():
args: list = sys.argv[1:]
args.sort()
if len(args) == 0:
file_a = input('第一个文件')
file_b = input('第二个文件')
merge(file_a, file_b)
elif len(args) == 1:
print_help()
# if args[0] in ['-h', '--help', '/?']:
# print_help()
# else:
# print_help()
elif len(args) % 2 == 0:
for i in range(0, len(args), 2):
merge(args[i], args[i + 1])
print('合并完成')
else:
print_help()
os.system('pause')
if __name__ == '__main__':
main()
效果
转载请注明:范的资源库 » 单面扫描正反面文件后一件合并软件小工具