使用Python轻松完成pdf的分割与合并

本文使用PyPdf4进行PDF的操作,请先安装相关的库。

二话不说,直接上代码:

import PyPDF4
#切割
def split_pdf_pages(input_path, output_path, start_page, end_page):
    with open(input_path, 'rb') as input_file, open(output_path, 'wb') as output_file:
        pdf_reader = PyPDF4.PdfFileReader(input_file)
        pdf_writer = PyPDF4.PdfFileWriter()
        for page_num in range(start_page - 1, end_page):
            pdf_writer.addPage(pdf_reader.getPage(page_num))

        pdf_writer.write(output_file)
#合并
def merge_pdfs(input_paths, output_path):
    pdf_writer = PyPDF4.PdfFileWriter()
    with open(output_path, 'wb') as output_file:
        for path in input_paths:
            with open(path, 'rb') as input_file:
                pdf_reader = PyPDF4.PdfFileReader(input_file)
                for page_num in range(pdf_reader.getNumPages()):
                    pdf_writer.addPage(pdf_reader.getPage(page_num))

                pdf_writer.write(output_file)
                
#调用合并时将分割部分注释掉即可,反之

#合并调用部分
output_path = "output.pdf"#输出文件的地址
input_paths = ["input1.pdf","input2.pdf"]#输入你需要合并的所有pdf,按先有后顺序合并
merge_pdfs(input_paths, output_path1)#调用合并

#分割调用部分
input_path = "input.pdf"    #输出需要分割的文件地址
output_path = "output.pdf"  #输出文件的地址
start_page=1    #开始分割的页
end_page=2  #结束页
split_pdf_pages(input_path, output_path,start_page,end_page)#调用分割函数

你可能感兴趣的:(pyhon与学习生活的那些事,python,pdf,开发语言)