使用Python合并PDF文件笔记

工作中,有多个原理图pdf文件,为了方便查找网标,所以需要把多个pdf文件进行合并

在网上查了以下使用python PyPDF2进行

源码如下

#encoding=gb18030
import os
import PyPDF2

##获取当前py文件所在路径
def get_exec_dir():
    '''获取当前执行文件所在的目录
     如果本程序打包成为一个文件,则执行目录应该在临时文件夹中
    '''
    #获取当前执行文件所在路径
    exe_path = os.path.realpath(__file__)
    print(f'主文件路径:{exe_path}')
    exe_dir = os.path.dirname(exe_path)
    print(f'主文件所在的目录:{exe_dir}')
    return exe_dir

def get_pdf_list(path):
    pdf_list = []
    for f in os.listdir(path):
        if f.endswith('.pdf') :
            pdf_list.append(f'{path}\\{f}')
    return pdf_list


def merge(path, pdfs):
    '''合并pdf'''
    pdf_merge = PyPDF2.PdfFileMerger()
    for pdf in pdfs:
        pdf_merge.append(pdf)
    pdf_merge.write(f'{path}\\test.pdf')

pdf_dir = get_exec_dir()
pdf_list = get_pdf_list(pdf_dir)
merge(pdf_dir, pdf_list)

把此文件和pdf文件放到同一目录运行

 运行python代码,最终在当前文件夹下生成test.pdf

此代码主要分成3个函数

第一个获取py文件所在路径

def get_exec_dir():
    '''获取当前执行文件所在的目录
     如果本程序打包成为一个文件,则执行目录应该在临时文件夹中
    '''
    #获取当前执行文件所在路径
    exe_path = os.path.realpath(__file__)
    print(f'主文件路径:{exe_path}')
    exe_dir = os.path.dirname(exe_path)
    print(f'主文件所在的目录:{exe_dir}')
    return exe_dir

这个函数返回py文件所在目录,这里使用__file__,如果直接在控制台敲代码则,__file__这个变量不存在,会导致这个函数出错

exe_path = os.path.realpath(__file__)

获取文件的绝对路径

exe_dir = os.path.dirname(exe_path)

返回文件的目录

第二个函数

def get_pdf_list(path):
    pdf_list = []
    for f in os.listdir(path):
        if f.endswith('.pdf') :
            pdf_list.append(f'{path}\\{f}')
    return pdf_list

列出path路径下所有的pdf文件

f.endswith('.pdf')  判断文件的后缀是否以 .pdf结尾

pdf_list.append(f'{path}\\{f}')  把pdf的绝对路径添加进列表

第三个函数,合并pdf

def merge(path, pdfs):
    '''合并pdf'''
    pdf_merge = PyPDF2.PdfFileMerger()
    for pdf in pdfs:
        pdf_merge.append(pdf)
    pdf_merge.write(f'{path}\\test.pdf')

pdf_merge = PyPDF2.PdfFileMerger() 生成pdf合并对象

接下来把所有pdf添加进合并对象中

pdf_merge.write(f'{path}\\test.pdf')  在pdf所在路径下生成test.pdf文件

记录点滴...

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jjinl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值