python PyPDF2 切割PDF文件
from PyPDF2 import PdfReader, PdfWriter def split_pdf(in_file,out_file,orientation="vertical",percent=0.5): """ :param in_file: 待拆分的pdf文件 :param out_path: 拆分成单页的pdf文件的存储路径 :param orientation: 切割方向 horizontal 水平切割 , vertical 垂直切割 :param percent: 百分比 第一个页面的百分比 :return: 无 """ with open(in_file, 'rb') as in_file: reader = PdfReader(in_file) writer = PdfWriter() number_of_pages = len(reader.pages) for i in range(number_of_pages): page = reader.pages[i] page2 = reader.pages[i].clone(PdfWriter(),True) if orientation == 'vertical': page.mediabox.upper_right = ( float(page.mediabox.right) * percent, page.mediabox.top ) page2.mediabox.lower_left = ( float(page2.mediabox.right) * percent, 0 ) else: page.mediabox.lower_right = ( page.mediabox.right, float(page.mediabox.top)*percent ) page2.mediabox.upper_right = ( page.mediabox.right, float(page.mediabox.top)*percent ) writer.add_page(page) writer.add_page(page2) with open(out_file,"wb") as fp: writer.write(fp) if __name__ == '__main__': in_File = './example.pdf' out_file = './out.pdf' # 生成输出文件 orientation = 'vertical' #切割方向 horizontal 水平切割 , vertical 垂直切割 percent = 0.5 # 百分比 第一个页面的百分比 split_pdf(in_File, out_file,orientation,percent)
安装库: pip install PyPDF2
标签:right,mediabox,python,percent,PyPDF2,file,PDF,page,out From: https://www.cnblogs.com/shaoyang0123/p/18489185