Python实现PDF文件切割保存到本地

实现从阿里oss读取数据去切割pdf

from PyPDF2 import PdfFileReader, PdfFileWriter
import logging, os
import uuid, tablestore as ots, time, json, oss2, io
import requests, shutil, urllib3
import pdfplumber
import subprocess
import re

from oss2.compat import to_bytes

'''
注意:
页数从0开始索引
range()是左闭右开区间
'''
oss_region = ''
oss_accessKeyId = ''
oss_accessKeySecret = ''
ossbucket = ''
oss_endpoint = ''


def handler(event, context):
    event_json = json.loads(event)
    print(event_json)
    split_pdf(event_json.get('file_path'), int(event_json.get('start_number')), int(event_json.get('end_number')),
              event_json.get('new_file_name'))


# 获取oss对象
def get_oss_client():
    auth = oss2.Auth(oss_accessKeyId, oss_accessKeySecret)
    oss_bucket = oss2.Bucket(auth, oss_endpoint, ossbucket)
    return oss_bucket


# 上传文件到oss
def upload_file(output_pdf, file_obj):
    oss_client = get_oss_client()
    oss_client.put_object('pdf_cut_file/' + output_pdf, file_obj)


# 在oss上获取文件
def get_file_in_oss(pdf_path):
    oss_client = get_oss_client()
    url = oss_client.sign_url('GET', pdf_path, 60, slash_safe=True)
    # print(object_stream)
    # with open('D:\\增值税专用发票加增值税普通发票(一份包含两种).pdf', 'wb') as local_fileobj:
    #     shutil.copyfileobj(object_stream, local_fileobj)
    return url


# 根据pdf路径打开pdf文件
def get_pdf(url):
    http = urllib3.PoolManager()
    temp = io.BytesIO()
    temp.write(http.request("GET", url).data)
    # pdf = pdfplumber.open(temp)
    return temp


def split_pdf(pdf_path, start_page, end_page, output_pdf):
    '''
    :param pdf_path:待分割的pdf文件在oss的文件路径
    :param start_page: 执行分割的开始页数
    :param end_page: 执行分割的结束位页数
    :param output_pdf: 保存切割后的文件名
    '''
    pdf_path = pdf_path.replace(' ','')
    output_pdf = output_pdf.replace(' ','')
    localtime1 = time.time()
    file_url = get_file_in_oss(pdf_path)
    localtime2 = time.time()
    print('获取ossurl')
    print((localtime2 - localtime1))
    # 根据url获取文件对象
    pdf = get_pdf(file_url)
    localtime3 = time.time()
    # 读取待分割的pdf文件
    input_file = PdfFileReader(pdf)
    # 实例一个 PDF文件编写器
    output_file = PdfFileWriter()
    localtime4 = time.time()
    # 把分割的文件添加在一起
    for i in range(start_page, end_page):
        output_file.addPage(input_file.getPage(i))
    localtime5 = time.time()
    print('切割完成')
    print((localtime5 - localtime4))
    # 将分割的文件输出保存
    pdf_name = output_pdf
    print('pdf_name:'+pdf_name)
    # file_path = re.split('.pdf/' + pdf_name,output_pdf)[len(re.split('.pdf/' + pdf_name,output_pdf)) - 2]
    # print('file_path:'+file_path)
    # subprocess.check_call("mkdir -p /tmp/pdfs/", shell=True)

    with open(pdf_name, 'wb') as f:
        output_file.write(f)

    localtime6 = time.time()
    print('保存到本地')
    print((localtime6 - localtime5))

    with open(pdf_name, 'rb') as file_obj:
        # file_obj.seek(0,os.SEEK_SET)
        # current = file_obj.tell()
        upload_file(output_pdf, file_obj)

    localtime7 = time.time()
    print('上传到oss')
    print((localtime7 - localtime6))
    print('删除本地文件')
    os.remove(pdf_name)

    # b = to_bytes(str(output_file))
    # upload_file(output_pdf, b)

if __name__ == '__main__':
	#oss文件地址,切割的页码,切割后的文件名
    split_pdf('original_ap/20221124_133409.pdf', 29, 30, "29.pdf")