当前位置: 首页 > news >正文

Python拆分PDF、Python合并PDF

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

代码如下(extract.py)

#!/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.namenew_pdf = fitz.Document()# 用第page_num页生成新的PDF文件index = page_num - 1new_pdf.insert_pdf(pdf, from_page=index, to_page=index)new_pdf.save(target)return targetdef 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 folderelse:return new_one(f, num)def main() -> None:file = SRC_FILEpage_num: int | None = Noneif sys.argv[1:]:if (a := sys.argv[1]).isdigit():page_num = int(a)elif (_p := Path(a)).is_file():file = _pif 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 = _pbreakelse: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 covermain()

合并的代码如下:

from pathlib import Pathimport fitzdef 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 targetmerge('1.pdf', '2.pdf')

http://www.lryc.cn/news/327717.html

相关文章:

  • SqlServer(4)经典总结大全-技巧总结-数据开发-基本函数-常识整理-经典面试题
  • ArcGIS矢量裁剪矢量
  • pygame用chatgpt绘制3d沿x轴旋转的
  • golang大小写规则的影响
  • 基于Java在线考试系统系统设计与实现(源码+部署文档)
  • 如何应对复杂软件工程的开发流程?
  • JAVA的NIO和BIO底层原理分析
  • Python学习从0到1 day18 Python可视化基础综合案例 1.折线图
  • HTML网站的概念
  • 【微服务】Nacos(配置中心)
  • 比较AI编程工具Copilot、Tabnine、Codeium和CodeWhisperer
  • 顺应互联网发展大潮流,红河农资招商火爆开启
  • 网络七层模型之传输层:理解网络通信的架构(四)
  • 微信小程序实现图片懒加载的4种方案
  • 各大pdf转word软件都用的哪家的ocr引擎?
  • 学习没有速成可言
  • 快速上手Pytrch爬虫之爬取某应图片壁纸
  • 如何在Apache Arrow中定位与解决问题
  • [ Linux ] git工具的基本使用(仓库的构建,提交)
  • 怎样去保证 Redis 缓存与数据库双写一致性?
  • RuoYi-Vue若依框架-新增子模块启动后,前端页面报接口404
  • node.js 常见命令
  • 教育信创,重磅发布!Coremail联合飞腾发布全场景教育信创白皮书
  • 滑动窗口_水果成篮_C++
  • 线程的状态:操作系统层面和JVM层面
  • 在Isaac-sim中弧度转四元数以及四元数转弧度的问题
  • 【计算机网络】高级IO模型
  • LabVIEW电动汽车直流充电桩监控系统
  • 前端学习<二>CSS基础——08-CSS属性:定位属性
  • 88. 合并两个有序数组(javascript)