python PDF拆分
时间: 2023-10-14 15:05:51 浏览: 47
在Python中,你可以使用PyPDF2库来拆分PDF文件。下面是一个简单的示例代码来演示如何使用PyPDF2来拆分PDF文件:
```
import PyPDF2
def split_pdf(input_file, output_file, start_page, end_page):
with open(input_file, 'rb') as file:
reader = PyPDF2.PdfFileReader(file)
writer = PyPDF2.PdfFileWriter()
for page in range(start_page - 1, end_page):
writer.addPage(reader.getPage(page))
with open(output_file, 'wb') as output:
writer.write(output)
# 使用示例
split_pdf('input.pdf', 'output.pdf', 1, 3)
```
上述代码中,我们定义了一个`split_pdf`函数,它接收输入文件路径、输出文件路径、起始页面和结束页面作为参数。然后,我们使用`PdfFileReader`从输入文件中读取PDF内容,并使用`PdfFileWriter`创建一个新的PDF写入器。接下来,我们循环遍历指定的页面范围,并使用`addPage`方法将每一页添加到写入器中。最后,我们使用`write`方法将写入器中的内容写入到输出文件中。
请注意,`start_page`和`end_page`参数是基于1的索引,也就是说第一页的索引是1而不是0。