python分页PDF

记录python分页PDF[待完善]

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

from PyPDF2 import PdfFileReader, PdfFileWriter


# PDF文件分割
def split_pdf():
    try:
        read_file = r"C:\Users\71694\Desktop\test.pdf" #  要分页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=r"C:\Users\71694\Desktop\1.txt" #  分页之后命名文件

        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)


if __name__ == '__main__':
    split_pdf()

命名文件1.txt格式

1-1 test [第一页到第一页分页为test.pdf]

1-1 test
2-2 test2
3-3 test3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我是小杰啊

谢谢您的打赏,是我最大的鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值