我有一些资料来源,并尝试编写代码以提取一些页面并创建pdf文件。 我有一个看起来像这样的列表
information = [(filename1,startpage1,endpage1), (filename2, startpage2, endpage2), ...,(filename19,startpage19,endpage19)].
这是我的代码。
import PyPDF2
for page in range(pdfReader.getNumPages()-1):
pdf_writer = PyPDF2.PdfFileWriter()
start = information[page][1]
end = information[page][2]
while start<end:
pdf_writer.addPage(pdfReader.getPage(start))
start+=1
output_filename = '{}_{}_page_{}.pdf'.format(information[page][0],information[page][1], information[page][2])
with open(output_filename,'wb') as out:
pdf_writer.write(out)
但是输出很奇怪。有些内部没有任何内容,有些只有一页。我该如何纠正?
答案 0 :(得分:1)
我已解决此问题。它是等号(start <= end)。
for page in range(len(information)):
pdf_writer = PyPDF2.PdfFileWriter()
start = information[page][1]
end = information[page][2]
while start<=end:
pdf_writer.addPage(pdfReader.getPage(start-1))
start+=1
if not os.path.exists(savepath):
os.makedirs(savepath)
output_filename = '{}_{}_page_{}.pdf'.format(information[page][0],information[page][1], information[page][2])
with open(output_filename,'wb') as out:
pdf_writer.write(out)
答案 1 :(得分:0)
完整代码+修改后的SSS'答案更便于携带。 现在,您可以提供多个PDF文件,其中包含要提取的页面的1个以上“段”。
from PyPDF2 import PdfFileReader, PdfFileWriter
# Note: index starts at 1 and is inclusive of the end.
# The following will extract page 3 of the pdf file.
pdfs = {'BMC PP template.pdf': ({'start': 3, 'end': 3},)}
for pdf, segments in pdfs.items():
pdf_reader = PdfFileReader(open(pdf, 'rb'))
for segment in segments:
pdf_writer = PdfFileWriter()
start_page = segment['start']
end_page = segment['end']
for page_num in range(start_page - 1, end_page):
pdf_writer.addPage(pdf_reader.getPage(page_num))
output_filename = f'{pdf}_{start_page}_page_{end_page}.pdf'
with open(output_filename,'wb') as out:
pdf_writer.write(out)