it编程 > 前端脚本 > Python

使用Python分割并高效处理PDF大文件详解

1人参与 2025-03-10 Python

在处理大型pdf文件时,将它们分解成更小、更易于管理的块通常是有益的。这个过程称为分区,它可以提高处理效率,并使分析或操作文档变得更容易。在本文中,我们将讨论如何使用python和为unstructured.io库将pdf文件划分为更小的部分。

我们将使用两个python库来完成此任务:

pypdf2:一个可以读、写、合并和分割pdf文件的库。

unstructured.io:一个可以使用文档图像分析模型分割pdf文档的库。

下面是完成这个任务的python代码:

from pypdf2 import pdfreader, pdfwriter
from unstructured.partition.pdf import partition_pdf

import os
from os import path

# create the output directory if it doesn't exist
# os.makedirs('./output', exist_ok=true)
path = path.abspath(path.dirname(__file__))

# pdf_file = path + '/sample01.pdf'

filename =  path + "/sample02.pdf"

# read the original pdf
input_pdf = pdfreader(f'{filename}')

batch_size = 2
num_batches = len(input_pdf.pages) // batch_size + 1

filename = path + "/output" 
# extract batches of 100 pages from the pdf
for b in range(num_batches):
    writer = pdfwriter()

    # get the start and end page numbers for this batch
    start_page = b * batch_size
    end_page = min((b+1) * batch_size, len(input_pdf.pages))

    # add pages in this batch to the writer
    for i in range(start_page, end_page):
        writer.add_page(input_pdf.pages[i])

    # save the batch to a separate pdf file
    batch_filename = f'{filename}-batch{b+1}.pdf'
    with open(batch_filename, 'wb') as output_file:
        writer.write(output_file)

    # now you can use the `partition_pdf` function from unstructured.io to analyze the batch
    elements = partition_pdf(filename=batch_filename)
    print(elements)
    # do something with `elements`...
    
    # this will process without issue
    # 抽取表格数据
	elements = partition_pdf("copy-protected.pdf", strategy="hi_res")

第一步:读pdf文件

首先,我们从pypdf2库导入必要的类:pdfreader和pdfwriter。pdfreader类用于读取原始pdf文件,该文件存储在名为“exam-prep”的子目录中。

步骤2:分区pdf

我们决定批大小,即pdf的每个块将包含的页数。在本例中,我们选择了100页的批处理大小,但这可以根据您的需要进行调整。

然后通过将pdf中的总页数除以批大小来计算批数量。添加1以确保在页面总数不是批大小的倍数时捕获所有剩余页面。

步骤3:写pdf块

接下来,循环遍历每个批处理,为每个批处理创建一个新的pdfwriter对象。对于每个批处理,我们计算起始页码和结束页码,并使用add_page方法将该范围内的每个页码添加到pdfwriter。

一旦添加了批处理的所有页面,我们将它们写入‘output’子目录下的新pdf文件中。每个块的文件名包括原始文件名和批号。

步骤4:分析pdf块

将pdf分成更小的块后,现在可以使用来自非结构化的partition_pdf函数。io库来分析每个批处理。该函数使用文档图像分析模型对pdf文档进行分段,并返回已解析pdf文档页面中出现的元素列表。

最后总结

将大型pdf文件划分为更小的块可以使它们更容易、容错和消耗更少的内存。

方法补充

下面小编为大家整理了其他python分割pdf的相关方法,感兴趣的可以了解下

方法一:批量分割pdf文件

现在,编写一个脚本来批量分割pdf文件。假设有一个大的pdf文件,需要每5页切割成一个小文件。

import pypdf2

def split_pdf(input_pdf, output_prefix, pages_per_file=5):
    with open(input_pdf, 'rb') as file:
        pdf_reader = pypdf2.pdffilereader(file)
        num_pages = pdf_reader.numpages

        for i in range(0, num_pages, pages_per_file):
            pdf_writer = pypdf2.pdffilewriter()
            output_pdf = f'{output_prefix}_{i // pages_per_file + 1}.pdf'

            for j in range(i, min(i + pages_per_file, num_pages)):
                page = pdf_reader.getpage(j)
                pdf_writer.addpage(page)

            with open(output_pdf, 'wb') as new_file:
                pdf_writer.write(new_file)

            print(f'已创建文件: {output_pdf}')

# 示例调用
split_pdf('large_file.pdf', 'output_split')

方法二:批量分割pdf

def main():
    directory = input("请输入pdf文件所在目录:")
    pdf_files = get_pdf_files(directory)
    split_rule = get_split_rule()
    output_directory = get_output_directory()

    for file in pdf_files:
        output_files = split_pdf(file, split_rule)
        save_output_files(output_files, output_directory)

    print("分割完成!")

if __name__ == "__main__":
    main()

到此这篇关于使用python分割并高效处理pdf大文件详解的文章就介绍到这了,更多相关python pdf处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

Python使用PDFMiner.six解析PDF数据详解

03-10

Python调用ollama本地大模型进行批量识别PDF

03-10

Python文本到语音转换库pyttsx3的安装及使用全面指南

03-10

Python+tkinter实现动态连接数据库

03-10

Python脚本实现音频和视频格式转换

03-10

Python中获取屏幕DPI值的不同方法总结

03-10

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论