from PyPDF2 import PdfFileReader, PdfFileWriter
# 1.以读的方式打开需要合并的两个pdf
reader1 = PdfFileReader(open('files/流畅的python.pdf', 'rb'))
reader2 = PdfFileReader(open('files/教育部学历证书电子注册备案表.pdf', 'rb'))
# 2.以写的方式打开一个空白的pdf
writer1 = PdfFileWriter()
# 3.遍历获取原文件的页面
for index in range(reader1.getNumPages()):
page = reader1.getPage(index)
if index % 2 == 0:
writer1.addPage(page)
writer1.addBlankPage() # 添加一个空白页
for index in range(reader2.getNumPages()):
page = reader2.getPage(index)
if index % 2 == 0:
writer1.addPage(page)
# 4.将writer1中的数据写入到pdf文件中
f = open('files/new_pdf.pdf', 'wb')
writer1.write(f)
f.close()
三、pypdf2添加水印
from PyPDF2 import PdfFileWriter, PdfFileReader
# 1.打开需要添加水印的pdf
reader1 = PdfFileReader(open('files/流畅的python.pdf', 'rb'))
# 2.打开提供水印的pdf
water_reader = PdfFileReader(open('files/学习路线图水印.pdf', 'rb'))
# 获取提供水印的页面
water = water_reader.getPage(0)
# 3.创建writer
writer = PdfFileWriter()
for index in range(reader1.getNumPages()):
# 获取原文件页面
page = reader1.getPage(index)
# 在原页面上添加水印
page.mergePage(water)
# 将添加过水印的页面添加到writer中
writer.addPage(page)
f = open('files/new_pdf1.pdf', 'wb')
writer.write(f)
f.close()
四、批量添加水印
from PyPDF2 import PdfFileWriter, PdfFileReader
import os
file = os.listdir('files2')
water_reader = PdfFileReader(open('files/学习路线图水印.pdf', 'rb'))
water = water_reader.getPage(0)
for x in file:
reader1 = PdfFileReader(open(f'files2/{x}', 'rb'))
writer = PdfFileWriter()
for index in range(reader1.getNumPages()):
page = reader1.getPage(index)
page.mergePage(water)
writer.addPage(page)
f = open(f'files3/{x}', 'wb')
writer.write(f)
f.close()