简单读写:
from PyPDF2 import PdfFileReader, PdfFileWriter
readFile = 'read.pdf'
writeFile = 'write.pdf'
# 获取一个 PdfFileReader 对象
pdfReader = PdfFileReader(open(readFile, 'rb'))
# 获取 PDF 的页数
pageCount = pdfReader.getNumPages()
print(pageCount)
# 返回一个 PageObject
page = pdfReader.getPage(i)
# 获取一个 PdfFileWriter 对象
pdfWriter = PdfFileWriter()
# 将一个 PageObject 加入到 PdfFileWriter 中
pdfWriter.addPage(page)
# 输出到文件中
pdfWriter.write(open(writeFile, 'wb'))
合并分割PDF:
from PyPDF2 import PdfFileReader, PdfFileWriter
def split_pdf(infn, outfn):
pdf_output = PdfFileWriter()
pdf_input = PdfFileReader(open(infn, 'rb'))
# 获取 pdf 共用多少页
page_count = pdf_input.getNumPages()
print(page_count)
# 将 pdf 第五页之后的页面,输出到一个新的文件
for i in range(5, page_count):
pdf_output.addPage(pdf_input.getPage(i))
pdf_output.write(open(outfn, 'wb'))
def merge_pdf(infnList, outfn):
pdf_output = PdfFileWriter()
for infn in infnList:
pdf_input = PdfFileReader(open(infn, 'rb'))
# 获取 pdf 总页数
page_count = pdf_input.getNumPages()
print(page_count)
for i in range(page_count):
pdf_output.addPage(pdf_input.getPage(i))
pdf_output.write(open(outfn, 'wb'))
if __name__ == '__main__':
infn = '导入的文件.pdf'
outfn = '导出的文件.pdf'
split_pdf(infn, outfn)