Python PyPDF2模块安装使用解析模块安装使用解析
这篇文章主要介绍了Python PyPDF2模块安装使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定
的参考学习价值,需要的朋友可以参考下
PyPDF2模块主要的功能是分割或合并PDF文件,裁剪或转换PDF文件中的页面。
0、安装PyPDF2的模块
pip install PyPDF2
1、常用的函数
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/15 13:38
# @Author : suk
# @File : pyxl.py
# @Software: PyCharm
import PyPDF2
reader = PyPDF2.PdfFileReader(open('linux.pdf', 'rb'))
print(reader.getNumPages()) # 获取pdf总页数
print(reader.isEncrypted) # 判断是否有加密
page = reader.getPage(4) # 获取第四页
print(page.extractText()) # 获取第四页的内容
print(reader.getDocumentInfo()) # 获取PDF元信息,即创建时间,作者,标题等
2、读取PDF文件,取指定页数,写入到硬盘上的示例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import PyPDF2
reader = PyPDF2.PdfFileReader(open('linux.pdf', 'rb'))
output = PyPDF2.PdfFileWriter()
output.addPage(reader.getPage(1))
output.addPage(reader.getPage(4))
output.addPage(reader.getPage(5))
print(output.getNumPages()) # 获取写入页的总页数
output.encrypt('123456')
outputStream = open('PyPDF2-output.pdf', 'wb')
output.write(outputStream)
outputStream.close()
3、读取PDF某一页,旋转180度后,写入到新的PDF文件的示例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import PyPDF2
reader = PyPDF2.PdfFileReader(open('linux.pdf', 'rb'))
page = reader.getPage(0) # 获取第0页
page.rotateClockwise(180) # 旋转180度
writer = PyPDF2.PdfFileWriter() # 创建PDF写入的对象
writer.addPage(page)
outputStream = open('rotate-page-test.pdf', 'wb') # 创建一个PDF文件
writer.write(outputStream) # 往文件写入PDF数据
outputStream.close() # 写入流
4、PDF增加水印的示例
评论10