我正在尝试将3页PDF分成3个单独的PDF文件。我一直在尝试使用以下代码:
from PyPDF2 import PdfFileReader, PdfFileWriter
pdf_file = open('Sample.pdf','rb')
pdf_reader = PdfFileReader(pdf_file)
pdf_writer = PdfFileWriter()
pageNumbers = pdf_reader.getNumPages()
for i in range (pageNumbers):
pdf_writer.addPage(pdf_reader.getPage(i))
split_motive = open('Sample_' + str(i+1) + '.pdf','wb')
pdf_writer.write(split_motive)
split_motive.close()
pdf_file.close()
但这似乎总是生成3个PDF文件:
有人可以帮忙吗?
答案 0 :(得分:2)
将pdf_writer = PdfFileWriter()
移动到循环体中。
from PyPDF2 import PdfFileReader, PdfFileWriter
pdf_file = open('Sample.pdf','rb')
pdf_reader = PdfFileReader(pdf_file)
pageNumbers = pdf_reader.getNumPages()
for i in range (pageNumbers):
pdf_writer = PdfFileWriter()
pdf_writer.addPage(pdf_reader.getPage(i))
split_motive = open('Sample_' + str(i+1) + '.pdf','wb')
pdf_writer.write(split_motive)
split_motive.close()
pdf_file.close()