python切割pdf文件

很簡(jiǎn)單直接上代碼,需要安裝PyPDF2,然后將下面代碼保存到cut_pdf.py

"""
前置:
pip install PyPDF2
python cut_pdf.py <fn.pdf> start_page end_page
"""
import os
import sys
from PyPDF2 import PdfReader, PdfWriter


def read_pdf(file_name):
    fp = open(file_name, 'rb')
    reader = PdfReader(fp)
    return reader.pages


def write_pdf(pages, to_fn):
    writer = PdfWriter()
    for p in pages:
        writer.add_page(p)
    with open(to_fn, 'wb') as ofp:
        writer.write(ofp)


def cut_pdf(file_path, b, e):
    pages = read_pdf(file_path)

    file_dir, file_name = os.path.split(file_path)
    file_base, file_ext = os.path.splitext(file_name)
    e = min(e, len(pages))
    new_file = file_path.replace(file_base, f'{file_base}__{e}')

    write_pdf(pages[b:e+1], new_file)
    return new_file


if __name__ == '__main__':
    if len(sys.argv) < 4:
        print('用法:\n\tpython <pdf_file> <start_page> <end_page>')
        exit(-1)
    pdf_file = sys.argv[1]
    start_page = sys.argv[2]
    end_page = sys.argv[3]
    ans = cut_pdf(pdf_file, int(start_page), int(end_page))
    print(f'文件寫(xiě)入到: {ans}')

看一下執(zhí)行效果:

$ python cut_pdf.py
用法:
    python <pdf_file> <start_page> <end_page>


$ python cut_pdf.py /Users/neozhao/Documents/圖書(shū)館/人文類/罪與罰.pdf 100 110
文件寫(xiě)入到: /Users/neozhao/Documents/圖書(shū)館/人文類/罪與罰_100_110.pdf

很簡(jiǎn)單吧,趕緊保存下來(lái),要用的時(shí)候直接用

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容