代码如下:
from PyPDF2 import PdfFileReader, PdfFileWriter pdf_reader = PdfFileReader(r"G:\6Tipdm\7python办公自动化\concat_pdf\时间序列.pdf") for page in range(pdf_reader.getNumPages()): pdf_writer = PdfFileWriter() pdf_writer.addPage(pdf_reader.getPage(page)) with open(f"G:\\6Tipdm\\7python办公自动化\\concat_pdf\\{page}.pdf", "wb") as out: pdf_writer.write(out)
结果如下:
2)旋转及排序pdf
① 旋转pdf
.rotateClockwise(90的倍数):顺时针旋转90度
.rotateCounterClockwise(90的倍数):逆时针旋转90度
from PyPDF2 import PdfFileReader, PdfFileWriter pdf_reader = PdfFileReader(r"G:\6Tipdm\7python办公自动化\concat_pdf\时间序列.pdf") pdf_writer = PdfFileWriter() for page in range(pdf_reader.getNumPages()): if page % 2 == 0: rotation_page = pdf_reader.getPage(page).rotateCounterClockwise(90) else: rotation_page = pdf_reader.getPage(page).rotateClockwise(90) pdf_writer.addPage(rotation_page) with open("G:\\6Tipdm\\7python办公自动化\\concat_pdf\\旋转.pdf", "wb") as out: pdf_writer.write(out) """ 上述代码中,我们循环遍历了这个pdf,对于偶数页我们逆时针旋转90°,对于奇数页我们顺时针旋转90°; 注意:旋转的角度只能是90的倍数; """
其中一页效果展示如下:
② 排序pdf
需求:我们有一个PDF文件,我们需要倒序排列,应该怎么做呢?
首先,我们来看python中,怎么倒叙打印一串数字,如下图所示。
那么倒序排列一个pdf,思路同上,代码如下:
from PyPDF2 import PdfFileReader, PdfFileWriter pdf_reader = PdfFileReader(r"G:\6Tipdm\7python办公自动化\concat_pdf\时间序列.pdf") pdf_writer = PdfFileWriter() for page in range(pdf_reader.getNumPages()-1, -1, -1): pdf_writer.addPage(pdf_reader.getPage(page)) with open("G:\\6Tipdm\\7python办公自动化\\concat_pdf\\倒序.pdf", "wb") as out: pdf_writer.write(out)
结果如下:
4、pdf批量加水印及加密、解密
1)批量加水印
from PyPDF2 import PdfFileReader, PdfFileWriter from copy import copy water = PdfFileReader(r"G:\6Tipdm\7python办公自动化\concat_pdf\水印.pdf") water_page = water.getPage(0) pdf_reader = PdfFileReader(r"G:\6Tipdm\7python办公自动化\concat_pdf\aa.pdf") pdf_writer = PdfFileWriter() for page in range(pdf_reader.getNumPages()): my_page = pdf_reader.getPage(page) new_page = copy(water_page) new_page.mergePage(my_page) pdf_writer.addPage(new_page) with open("G:\\6Tipdm\\7python办公自动化\\concat_pdf\\添加水印后的aa.pdf", "wb") as out: pdf_writer.write(out) """ 这里有一点需要注意:进行pdf合并的时候,我们希望“水印”在下面,文字在上面,因此是“水印”.mergePage(“图片页”) """
结果如下:
2)批量加密、解密
这里所说的“解密”,是在知道pdf的密码下,去打开pdf,而不是暴力破解;
① 加密pdf
from PyPDF2 import PdfFileReader, PdfFileWriter pdf_reader = PdfFileReader(r"G:\6Tipdm\7python办公自动化\concat_pdf\时间序列.pdf") pdf_writer = PdfFileWriter() for page in range(pdf_reader.getNumPages()): pdf_writer.addPage(pdf_reader.getPage(page)) # 添加密码 pdf_writer.encrypt("a123456") with open("G:\\6Tipdm\\7python办公自动化\\concat_pdf\\时间序列.pdf", "wb") as out: pdf_writer.write(out)
结果如下: