Python拆分PDF、Python合并PDF

WPS能拆分合并,但却是要输入编辑密码,我没有。故写了个脚本来做拆分,顺便附上合并的代码。

代码如下(extract.py)

python 复制代码
#!/usr/bin/env python
"""PDF拆分脚本(需要Python3.10+)

Usage::
    $ python extract.py <pdf-file>
"""
import os
import sys
from pathlib import Path

# pip install PyMuPDF
import fitz  # type:ignore[import-untyped]

SRC_FILE = Path.home() / "Downloads" / "yasi.pdf"


def new_one(pdf: fitz.Document, page_num: int, parent: Path | None = None) -> Path:
    target = Path(f"{page_num}.pdf")
    if parent is not None:
        target = parent / target.name
    new_pdf = fitz.Document()
    # 用第page_num页生成新的PDF文件
    index = page_num - 1
    new_pdf.insert_pdf(pdf, from_page=index, to_page=index)
    new_pdf.save(target)
    return target


def extract(
    file: Path,
    num: int | None = None,
) -> Path:
    """拆分PDF

    :param file: 文件路径
    :param num: 要拆分出哪一页,如果传None或不传,则每一页都拆分出来
    """
    with fitz.open(file) as f:
        if num is None:
            folder = Path(file.stem)
            if not folder.exists():
                print(f"Directory {folder} created!")
                folder.mkdir()
            print(f"Total pages of {file} is {f.page_count}.")
            for num in range(1, f.page_count + 1):
                new_one(f, num, folder)
            return folder
        else:
            return new_one(f, num)


def main() -> None:
    file = SRC_FILE
    page_num: int | None = None
    if sys.argv[1:]:
        if (a := sys.argv[1]).isdigit():
            page_num = int(a)
        elif (_p := Path(a)).is_file():
            file = _p
            if sys.argv[2:] and sys.argv[2].isdigit():
                page_num = int(sys.argv[2])
        elif _p.suffix.lower() == ".pdf":
            print(f"文件`{_p}`不存在!")
    elif not file.exists():
        while True:
            a = input("请输入要拆分的PDF文件路径:").strip()
            if "~" in a:
                a = os.path.expanduser(a)
            if (_p := Path(a)).is_file():
                file = _p
                break
            else:
                print(f"文件{_p}不存在,请重新输入。\n")
    dst = extract(file, page_num)
    if dst.is_file():
        print(f"Save file to {dst}")
    else:
        print(f"Save files to {dst}{os.sep}")


if __name__ == "__main__":  # pragma: no cover
    main()

合并的代码如下:

python 复制代码
from pathlib import Path

import fitz


def merge(*files: str, new_name: str | None = None, verbose=True) -> Path:
    ps = [Path(i) for i in files]
    if new_name is None:
        new_name = '_'.join(i.stem for i in ps) + '.pdf'
    target = Path(new_name)
    new_pdf = fitz.Document()
    for p in ps:
        with fitz.open(p) as f:
            new_pdf.insert_pdf(f)
    new_pdf.save(target)
    if verbose:
        print(f'Save file to {target}')
    return target


merge('1.pdf', '2.pdf')
相关推荐
GIS阵地41 分钟前
QgsRasterDataProvider 完整详解(QGIS 3.40.13 C++)
开发语言·c++·qt·开源软件·qgis
yaoxin5211231 小时前
462. Java 反射 - 获取声明类与封闭类
java·开发语言·python
阿里嘎多学长2 小时前
2026-07-14 GitHub 热点项目精选
开发语言·程序员·github·代码托管
中微极客2 小时前
解锁LLM开发全栈能力:Python + LangChain + RAG 工程实战指南
人工智能·python·langchain
hhzz2 小时前
Barbershop:基于GAN和分割Mask的图像合成技术——从理论到实战全解析
图像处理·人工智能·python·深度学习·计算机视觉
charlie1145141913 小时前
Cinux: 为大内核铺路
开发语言·c++·操作系统·现代c++
2501_914245933 小时前
C语言设计模式详解:从理论到实践的完整指南
c语言·开发语言·设计模式
Hazenix3 小时前
Go 指南:一篇文章速通 Golang
开发语言·后端·golang
灯澜忆梦3 小时前
GO_复合类型---指针
开发语言·后端·golang
Ulyanov3 小时前
雷达导引头Python仿真框架:GPU加速、6-DOF模型与半实物仿真接口
开发语言·python·雷达信号处理·雷达导引头