python PyPDF2 切割PDF文件

python PyPDF2 切割PDF文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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

文档:https://files.cnblogs.com/files/shaoyang0123/PyPDF2.txt.zip?t=1729485644&download=true 

posted on   少杨  阅读(43)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示