文章目录

  • 概述
  • 安装
  • 一、The PdfFileReader Class
    • 1、getNumPages()
    • 2、getPage(pageNumber)
  • 二、The PdfFileWriter Class
    • 1、addPage(page)
    • 2、write(stream)
  • 三、The PdfFileMerger Class
    • 方法1、append()
    • 方法2、merge()
    • 方法3、write()
  • 实例一:删除
  • 实例二:合并

概述

PyPDF2是Python中用于对PDF操作的第三方库,提供了删除、合并、裁剪、转换等操作
最主要有四个类:
The PdfFileReader Class
The PdfFileMerger Class
The PageObject Class
The PdfFileWriter Class

安装

打开命令行键入

pip install PyPDF2

一、The PdfFileReader Class

 PyPDF2.PdfFileReader(stream, strict=True, warndest=None, overwriteWarnings=True)

Parameters:
stream – A File object or an object that supports the standard read and seek methods similar to a File object. Could also be a string representing a path to a PDF file.

strict (bool) – Determines whether user should be warned of all problems and also causes some correctable problems to be fatal. Defaults to True.

warndest – Destination for logging warnings (defaults to sys.stderr).

overwriteWarnings (bool) – Determines whether to override Python’s warnings.py module with a custom implementation (defaults to True).

1、getNumPages()

Calculates the number of pages in this PDF file.

Returns: number of pages
Return type: int
Raises PdfReadError:
if file is encrypted and restrictions prevent this action.

2、getPage(pageNumber)

Retrieves a page by number from this PDF file.

Parameters: pageNumber (int)
– The page number to retrieve (pages begin at zero)
Returns: a PageObject instance.
Return type: PageObject

二、The PdfFileWriter Class

class PyPDF2.PdfFileWriter
This class supports writing PDF files out, given pages produced by another class (typically PdfFileReader).

1、addPage(page)

Adds a page to this PDF file. The page is usually acquired from a PdfFileReader instance.

Parameters: page (PageObject) – The page to add to the document. Should be an instance of PageObject

2、write(stream)

Writes the collection of pages added to this object out as a PDF file.

Parameters: stream – An object to write the file to. The object must support the write method and the tell method, similar to a file object.

三、The PdfFileMerger Class

Initializes a PdfFileMerger object. PdfFileMerger merges multiple PDFs into a single PDF. It can concatenate, slice, insert, or any combination of the above.
初始化一个PdfFileMerger对象,PdfFileMerger 用来将多个PDF合并为一个PDF,它能够连接,切割,插入或者以上的任意组合

See the functions merge() (or append()) and write() for usage information.

Parameters: strict (bool) – Determines whether user should be warned of all problems and also causes some correctable problems to be fatal. Defaults to True.

方法1、append()

append(fileobj, bookmark=None, pages=None, import_bookmarks=True)

Identical to the merge() method, but assumes you want to concatenate all pages onto the end of the file instead of specifying a position.
和merge()方法相同,但假定的是你想要把全部页面连接到文件的最后而不是指定位置

Parameters:
fileobj – A File Object or an object that supports the standard read and seek methods similar to a File Object. Could also be a string representing a path to a PDF file.
一个文件对象(python中用open()创建的对象)或者类似文件对象的能够支持标准读取和寻找方法的对象,也可以是一个代表指向PDF文件路径的字符串
bookmark (str) – Optionally, you may specify a bookmark to be applied at the beginning of the included file by supplying the text of the bookmark.
pages – can be a Page Range or a (start, stop[, step]) tuple to merge only the specified range of pages from the source document into the output document.
可以是一个页码序列或者一个(start, stop[, step])元组,用来合并指定范围的源文件页面到输出文件

import_bookmarks (bool) – You may prevent the source document’s bookmarks from being imported by specifying this as False.

在这里插入代码片

方法2、merge()

merge(position, fileobj, bookmark=None, pages=None, import_bookmarks=True)

Merges the pages from the given file into the output file at the specified page number.
从指定位置合并来自给定文件的页面到输出文件

Parameters:
position (int) – The page number to insert this file. File will be inserted after the given number.
插入文件的页码数,将插入到给定页数的后面
0口1 口2 口3
fileobj – A File Object or an object that supports the standard read and seek methods similar to a File Object. Could also be a string representing a path to a PDF file.
bookmark (str) – Optionally, you may specify a bookmark to be applied at the beginning of the included file by supplying the text of the bookmark.
pages – can be a Page Range or a (start, stop[, step]) tuple to merge only the specified range of pages from the source document into the output document.

import_bookmarks (bool) – You may prevent the source document’s bookmarks from being imported by specifying this as False.

注意:position和pages均指的是下图绿色数字,pages的范围是绿色数字之间囊括的页面

方法3、write()

write(fileobj)
Writes all data that has been merged to the given output file.
将所有被合并的数据写入到给定的输出文件中

Parameters: fileobj – Output file. Can be a filename or any kind of file-like object.
输出文件,可以是一个文件名或者所有类似文件对象的对象

实例一:删除

#PDF_delete.py
from PyPDF2 import PdfFileWriter, PdfFileReaderdef PDF_delete(index):output = PdfFileWriter()  # 声明一个用于输出PDF的实例input1 = PdfFileReader(open("C:/Users/Yuanzheng/Desktop/Test1.pdf", "rb"))  # 读取本地PDF文件pages = input1.getNumPages()  # 读取文档的页数for i in range(pages):if i + 1 in index:continue  # 待删除的页面output.addPage(input1.getPage(i))  # 读取PDF的第i页,添加到输出Output实例中outputStream = open("C:/Users/Yuanzheng/Desktop/Test-Output1.pdf", "wb")output.write(outputStream)  # 把编辑后的文档保存到本地
PDF_delete([2])

实例二:合并

#PDF_merger.py
from PyPDF2 import PdfFileMergermerger = PdfFileMerger()input1 =open("C:/Users/Yuanzheng/Desktop/Test1.pdf","rb")
input2  = open("C:/Users/Yuanzheng/Desktop/Test2.pdf","rb")merger.append(fileobj= input1)
merger.merge(position=0,fileobj=input2,pages=(1,3))output = open("C:/Users/Yuanzheng/Desktop/PyPDF-Output2.pdf","wb")
merger.write(output)

Reference:https://pythonhosted.org/PyPDF2/PageObject.html

Python之利用PyPDF2库实现对PDF的删除和合并相关推荐

  1. python读取pdf文档书签 bookmark_Python利用PyPDF2库获取PDF文件总页码实例

    Python中可以利用PyPDF2库来获取该pdf文件的总页码,可以根据下面的方法一步步进行下去: 1.首先,要安装PyPDF2库,利用以下命令即可: pip install PyPDF2 2.接着, ...

  2. python读取扫描形成的pdf_Python利用PyPDF2库获取PDF文件总页码实例

    Python中可以利用PyPDF2库来获取该pdf文件的总页码,可以根据下面的方法一步步进行下去: 1.首先,要安装PyPDF2库,利用以下命令即可: pip install PyPDF2 2.接着, ...

  3. Python利用PyPDF2库获取PDF文件总页码

    Python中可以利用PyPDF2库来获取该pdf文件的总页码,可以根据下面的方法一步步进行下去: 1.首先,要安装PyPDF2库,利用以下命令即可: pip install PyPDF2 2.接着, ...

  4. 用python的openpyxl库实现对excel工作表的自动化操作

    用python的openpyxl库实现对excel工作表的自动化操作 用python的openpyxl库读取excel工作表,批量建立工作表,批量修改工作表标题,批量设置单元格样式,批量调整打印设置. ...

  5. ML之nyoka:基于nyoka库利用LGBMClassifier模型实现对iris数据集训练、保存为pmml模型并重新载入pmml模型进而实现推理

    ML之nyoka:基于nyoka库利用LGBMClassifier模型实现对iris数据集训练.保存为pmml模型并重新载入pmml模型进而实现推理 目录 基于nyoka库利用LGBMClassifi ...

  6. ML之K-means:基于K-means算法利用电影数据集实现对top 100 电影进行文档分类

    ML之K-means:基于K-means算法利用电影数据集实现对top 100 电影进行文档分类 目录 输出结果 实现代码 输出结果 先看文档分类后的结果,一共得到五类电影: 实现代码 # -*- c ...

  7. ML之H-Clusters:基于H-Clusters算法利用电影数据集实现对top 100电影进行文档分类

    ML之H-Clusters:基于H-Clusters算法利用电影数据集实现对top 100电影进行文档分类 目录 输出结果 实现代码 输出结果 先看输出结果 实现代码 # -*- coding: ut ...

  8. 利用胶囊网络实现对CIFAR10分类

    利用胶囊网络实现对CIFAR10分类 数据集:CIFAR-10数据集由10个类中的60000个32x32彩色图像组成,每个类有6000个图像.有50000个训练图像和10000个测试图像. 实验:搭建 ...

  9. Python:利用collections库实现统计单个字或单个字母的频率统计并进行降序输出、统计一个列表内重复元素并以字典形式输出

    Python:利用collections库实现统计单个字或单个字母的频率统计并进行降序输出.统计一个列表内重复元素并以字典形式输出 目录 利用collections库实现统计单个字或单个字母的频率统计 ...

最新文章

  1. 社交系统/社群系统ThinkSNS+ alpha.2 版本发布!
  2. [树状数组] Inverse
  3. 【放置奇兵】新版公会战问题
  4. 二叉树先序,中序,后序,层次遍历(数据结构)
  5. jax-rs jax-ws_对状态代码使用JAX-RS异常
  6. c语言中循环结构的作用,C语言中对于循环结构优化的一些入门级方法简介
  7. 重庆最狠的火锅,都是用来泡脚的
  8. 微信小程序不支持打开非业务域名_开达应用五端合一:抖音/头条小程序基础配置...
  9. u8虚拟服务器端口,用友u8服务器参数配置
  10. linux--私钥登陆
  11. 词法分析(三):有限自动机DFA与NFA
  12. 亚马逊关联账号有哪些类型
  13. 【Axure】实例:微信登录
  14. 常用标点符号的英文名称
  15. java thread 匿名_Java 匿名内部类
  16. 了不起的Chrome浏览器(6):Chrome 94开始WebGPU试用,Web的图像渲染及机器学能力更强了
  17. 2021 回头看看这一年
  18. 【蓝桥杯Python组】既约分数
  19. Unity 2020.3.17 从UnityHub下载安装失败(含Android)
  20. magento的Cannot initialize the indexer process解决方法

热门文章

  1. 2021.1.19课程摘要[上](逻辑教育-王劲胜)
  2. 【Python学习教程】Python编程环境搭建
  3. VLC接收网络串流缓冲时间的计算
  4. Java面试准备(四)——Java8特性
  5. Esri与欧盟委员会签订许可协议
  6. 手机 听广播 不用 耳机 android,FM手机调频收音机无广告
  7. 警惕诈骗:在俄罗斯000Pay声称支持…
  8. 怎样用计算机计算分数除法,分数除法的计算方法
  9. Springboot毕设项目青年创业众筹网站2rz86java+VUE+Mybatis+Maven+Mysql+sprnig)
  10. 消息中间件的应用——谈谈秒杀(转)