python拆分pdf文件

#!/usr/bin/env python
# coding=utf-8

from PyPDF2 import PdfFileReader, PdfFileWriter


# PDF文件分割
def split_pdf():
    try:
        read_file = input("请输入要拆分的PDF名字(例如test.pdf):")
        fp_read_file = open(read_file, 'rb')
        pdf_input = PdfFileReader(fp_read_file)  # 将要分割的PDF内容格式话
        page_count = pdf_input.getNumPages()  # 获取PDF页数
        print("该文件共有{}页".format(page_count))  # 打印页数

        out_detail=input("请输入拆分规则文件名")

        with open(out_detail, 'r',True,'utf-8')as fp:
            # print(fp)
            txt = fp.readlines()
            # print(txt)
            for detail in txt:  # 打开分割标准文件
                # print(type(detail))
                pages, write_file = detail.split()  # 空格分组
               #  write_file, write_ext = os.path.splitext(write_file)  # 用于返回文件名和扩展名元组
                pdf_file = f'{write_file}.pdf'
                # liststr=list(map(int, pages.split('-')))
                # print(type(liststr))
                start_page, end_page = list(map(int, pages.split('-')))  # 将字符串数组转换成整形数组
                start_page -= 1
                try:
                    print(f'开始分割{start_page}页-{end_page}页,保存为{pdf_file}......')
                    pdf_output = PdfFileWriter()  # 实例一个 PDF文件编写器
                    for i in range(start_page, end_page):
                        pdf_output.addPage(pdf_input.getPage(i))
                    with open(pdf_file, 'wb') as sub_fp:
                        pdf_output.write(sub_fp)
                    print(f'完成分割{start_page}页-{end_page}页,保存为{pdf_file}!')
                except IndexError:
                    print(f'分割页数超过了PDF的页数')
        # fp.close()
    except Exception as e:
        print(e)
    # finally:
    #     fp_read_file.close()



# def main():
#     fire.Fire(split_pdf)
#
# if __name__ == '__main__':
#     main()
if __name__ == '__main__':
    print("请在当前路径下建立一个拆分规则文本文件")
    print("例如:1-2 try,表示把第一页和第二页拆分出来,命名为try.pdf,一行写一次拆分")
    split_pdf()


    原文作者:追梦小狂魔
    原文地址: https://blog.csdn.net/qq_15557299/article/details/105101919
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞