• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python处理pdf文件库 – PyPDF2详解

python 搞java代码 3年前 (2022-05-24) 21次浏览 已收录 0个评论

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

安装

1. RPM式系统(Redhat、CentOS)

pip install <a href="https://www.gaodaima.com/tag/pypdf" title="查看更多关于pypdf的文章" target="_blank">pypdf</a>2

www#gaodaima.com来源gaodai#ma#com搞*代#码网搞代码

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

pip install pypdf2
apt install <a href="https://www.gaodaima.com/tag/python" title="查看更多关于python的文章" target="_blank">python</a>-pypdf2

3. Windows

pip install pypdf2

使用

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

简单读写

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'))

合并分割 PDF

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)

其他命令

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

pdfWriter.appendPagesFromReader(reader)

添加书签:

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

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python处理pdf文件库 – PyPDF2详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址