python拆分pdf 最新版本代码
时间: 2023-11-05 17:04:43 浏览: 34
我了解您需要帮助拆分PDF文件,并提供Python代码。以下是一个可以使用的示例:
```python
import PyPDF2
def split_pdf(input_pdf, start_page, end_page, output_pdf):
# Open the PDF file
pdf_file = open(input_pdf, 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
# Create a new PDF writer object
pdf_writer = PyPDF2.PdfFileWriter()
# Loop through each page in the input PDF
for page_num in range(start_page - 1, end_page):
# Add the page to the PDF writer object
pdf_writer.addPage(pdf_reader.getPage(page_num))
# Write the output PDF file
with open(output_pdf, 'wb') as out_file:
pdf_writer.write(out_file)
# Close the input PDF file
pdf_file.close()
# Example usage:
split_pdf('input.pdf', 1, 5, 'output.pdf')
```
在上面的示例中,我们使用PyPDF2库打开输入PDF文件并读取所需页面。然后,我们创建一个新的PDF写入器对象并将所需页面添加到其中。最后,我们将输出PDF文件写入磁盘,并关闭输入文件。要使用此示例,将文件名替换为实际的PDF文件名,并指定要拆分的页面范围和输出文件名。