工作中,我们有时需要将pdf文件中的指定页提取出来,另存为新的pdf文件。
例如:我想提取 example.pdf 的第 [3, 6, 9] 页,然后另存为 new.pdf 。话不多说,上代码:
import PyPDF2
def split_pdf(input_pdf_path, choose_pages):
with open(input_pdf_path, 'rb') as file:
reader = PyPDF2.PdfReader(file)
output_pdf_path = f"new.pdf"
writer = PyPDF2.PdfWriter()
for page_number in choose_pages:
writer.add_page(reader.pages[page_number - 1])
with open(output_pdf_path, 'wb') as output_file:
writer.write(output_file)
# 使用示例
input_pdf_path = 'example.pdf' # 输入的PDF文件路径
choose_pages = [3, 6, 9]
split_pdf(input_pdf_path, choose_pages)
如果你还没有安装 PyPDF2,请安装
pip install PyPDF2