分割及合并

利用pypdf2分割PDF,这里按照页码进行分割。PdfFileReader读取PDF,PdfFileWriter输出写入。

from PyPDF2 import PdfFileReader,PdfFileWriter
pdf_reader=PdfFileReader('1.pdf') # 读取pdf文件
# 循环读取每一页 pdf_reader.getNumPages()会返回页码
for page in range(pdf_reader.getNumPages()): 
    pdf_writer=PdfFileWriter() # 创建pdf实例
    pdf_writer.addPage(pdf_reader.getPage(page)) # getPage(page)获取某一页数据
    with open(f'./分割后的pdf文件{page}.pdf','wb') as out:
        pdf_writer.write(out)

将刚才分割的PDF再次合并为一个文件。

from PyPDF2 import PdfFileReader,PdfFileWriter

pdf_writer=PdfFileWriter() # 创建一个实例
for page in range(44): # 循环页码
    pdf_reader=PdfFileReader(f'./分割后的pdf文件{page}.pdf')
    for page in range(pdf_reader.getNumPages()):
        pdf_writer.addPage(pdf_reader.getPage(page))
with open('new_1.pdf','wb') as out:
    pdf_writer.write(out)

旋转PDF某一页

使用.rotateClockwise(90的倍数)方法,顺时针旋转90度;使用.rotateCounterClockwise(90的倍数)方法,逆时针旋转90度:

from PyPDF2 import PdfFileReader,PdfFileWriter

pdf_reader=PdfFileReader('1.pdf')
pdf_writer=PdfFileWriter()
page=pdf_reader.getPage(0).rotateClockwise(90)
pdf_writer.addPage(page)

page=pdf_reader.getPage(1).rotateCounterClockwise(90)
pdf_writer.addPage(page)
with open('rotate.pdf','wb') as f:
    pdf_writer.write(f)

排序PDF页面

倒序排列:

from PyPDF2 import PdfFileReader,PdfFileWriter

pdf_reader=PdfFileReader('1.pdf')
pdf_writer=PdfFileWriter()


for page in range(pdf_reader.getNumPages()-1,-1,-1):
    pdf_writer.addPage(pdf_reader.getPage(page))
with open('reordered.pdf','wb') as f:
    pdf_writer.write(f)

发表评论

后才能评论