用python写pdf_python写个合并pdf的小工具

这段代码展示了一个使用PyPDF4库合并PDF文件的Python函数。它遍历指定目录下的所有PDF文件,按照文件名排序,并将它们合并到一个名为'merged.pdf'的新文件中。如果遇到加密的PDF文件,会提示用户输入密码。
摘要由CSDN通过智能技术生成

[Python] 纯文本查看 复制代码import re

from PyPDF4.pdf import PdfFileReader as pr, PdfFileWriter as pw

def MergePDF(dir_path):

pdf_files = list()

merged_file = pw()

for path, _, files in os.walk(dir_path):

pdf_files.extend([os.path.join(path, f)

for f in files if f.lower().endswith('.pdf')]) # 遍历当前文件夹下所有pdf文件并组合成相对路径

pdf_files.sort(key=lambda i: int(re.findall(r'(\d+).*?', i)

[0]) if re.findall(r'(\d+).*?', i) else -1) # 按照路径排序(没有数字的在前面, 有数字的从小到大排序)

for pdf_file in pdf_files:

print(pdf_file)

try:

pdf = pr(open(pdf_file, "rb"))

except:

print(f'{pdf_file}无法解析')

continue

if pdf.isEncrypted:

print(f'{pdf_file} 是加密文件')

res = input('输入密码(回车键跳过)')

while res:

try:

pdf.decrypt(res) # pdf 解密

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值