加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python处理pdf文件库:PyPDF2的简单示例

发布时间:2020-12-17 07:09:20 所属栏目:Python 来源:网络整理
导读:对python这个高级语言感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧! 工作中可能会涉及处理pdf文件,PyPDF2就是这样一个库, 使用它可以轻松的处理pdf文件,它提供了读、写、分割、合并、文件转换等多种操作。官方地址:http://mstamy2
对python这个高级语言感兴趣的小伙伴,下面一起跟随编程之家 52php.cn的小编两巴掌来看看吧!

工作中可能会涉及处理pdf文件,PyPDF2就是这样一个库, 使用它可以轻松的处理pdf文件,它提供了读、写、分割、合并、文件转换等多种操作。官方地址:http://mstamy2.github.io/PyPDF2/

安装

1. RPM式系统(Redhat、CentOS)


pip install pypdf2

# End www.52php.cn

2. DEB式系统(Debian、Ubuntu)以下任一


pip install pypdf2
apt install python-pypdf2

# End www.52php.cn

3. Windows


pip install pypdf2

# End www.52php.cn

使用

PyPDF2 包含了 PdfFileReader PdfFileMerger PageObject PdfFileWriter 四个常用的主要 Class。

简单读写


# @param Python处理pdf文件库 - PyPDF2详解
# @author 编程之家 52php.cn|52php.cn 

from PyPDF2 import PdfFileReader,PdfFileWriter
readFile = 'read.pdf'
writeFile = 'write.pdf'
# 获取一个 PdfFileReader 对象
pdfReader = PdfFileReader(open(readFile,'rb'))
# 获取 PDF 的页数
pageCount = pdfReader.getNumPages()
print(pageCount)
# 返回一个 PageObject
page = pdfReader.getPage(i)
# 获取一个 PdfFileWriter 对象
pdfWriter = PdfFileWriter()
# 将一个 PageObject 加入到 PdfFileWriter 中
pdfWriter.addPage(page)
# 输出到文件中
pdfWriter.write(open(writeFile,'wb'))

# End www.52php.cn

 

合并分割 PDF


# @param Python处理pdf文件库 - PyPDF2详解
# @author 编程之家 52php.cn|52php.cn 

from PyPDF2 import PdfFileReader,PdfFileWriter
def split_pdf(infn,outfn):
    pdf_output = PdfFileWriter()
    pdf_input = PdfFileReader(open(infn,'rb'))
    # 获取 pdf 共用多少页
    page_count = pdf_input.getNumPages()
    print(page_count)
    # 将 pdf 第五页之后的页面,输出到一个新的文件
    for i in range(5,page_count):
        pdf_output.addPage(pdf_input.getPage(i))
    pdf_output.write(open(outfn,'wb'))
def merge_pdf(infnList,outfn):
    pdf_output = PdfFileWriter()
    for infn in infnList:
        pdf_input = PdfFileReader(open(infn,'rb'))
        # 获取 pdf 共用多少页
        page_count = pdf_input.getNumPages()
        print(page_count)
        for i in range(page_count):
            pdf_output.addPage(pdf_input.getPage(i))
    pdf_output.write(open(outfn,'wb'))
if __name__ == '__main__':
    infn = 'infn.pdf'
    outfn = 'outfn.pdf'
    split_pdf(infn,outfn)

# End www.52php.cn

其他命令

如果是要修改一个已有的 pdf 文件,可以将 reader 的页面添加到 writer 中:

pdfWriter.appendPagesFromReader(reader)

添加书签:

pdfWriter.addBookmark(title,pagenum,parent=parent)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读