python代码把截取任意页的pdf:比如你有一个pdf文件1.pdf,共有30页,但是,你想把其中的10-20页截取出来保存成新的pdf,名为2.pdf,可以使用下面代码
from PyPDF2 import PdfReader, PdfWriter# 输入和输出文件的路径
input_pdf_path = 'E:/pythonworking/file/pdf_merge/2018_RNA G-quadruplexes are globally unfolded in eukaryotic cells and depleted in bacteria.pdf'
output_pdf_path = 'E:/pythonworking/file/pdf_merge/2018_RNA G-quadruplexes are globally unfolded in eukaryotic cells and depleted in bacteria1.pdf'# 创建PDF阅读器和写入器对象
reader = PdfReader(input_pdf_path)
writer = PdfWriter()# 循环遍历指定的页面范围,这里是第4到第6页(注意页码从0开始计算)
for i in range(0, 20): # 因为页码从0开始,所以第4页是索引3,第6页是索引5writer.add_page(reader.pages[i])# 将选定的页面写入到新的PDF文件中
with open(output_pdf_path, 'wb') as output_pdf:writer.write(output_pdf)print("PDF pages extracted successfully.")