Last active 1716454334

将多个PDF文件合并为一个文件,可以指定要合并的页码

ryano's Avatar ryano revised this gist 1716454334. Go to revision

No changes

ryano's Avatar ryano revised this gist 1716454309. Go to revision

2 files changed, 52 insertions

README.md(file created)

@@ -0,0 +1,21 @@
1 + # PDF文件合并脚本
2 +
3 + 将多个PDF文件合并为一个文件,可以指定要合并的页码
4 +
5 + 用法示例:`python3 pdf_merge.py -i file1.pdf,1-3 file2.pdf -o out.pdf`
6 +
7 + 上述指令将`file1.pdf`的`1`到`3`页,`file2.pdf`的所有页面顺序合并到`out.pdf`文件中
8 +
9 + ## 参数说明
10 +
11 + - `-i` 参数用来指定需要合并的文件,可以指定多个文件,每个文件用空格隔开,文件名后面用逗号开始指定页码,两个页码之间用`-`横杠分开,如果不指定页码则合并所有页面;
12 +
13 + - `-o` 参数用来指定输出文件的名称。
14 +
15 + ## 依赖包安装
16 +
17 + 此脚本依赖`PyPDF2`,需要先使用下面的命令先安装
18 +
19 + ```bash
20 + pip install PyPDF2
21 + ```

pdf_merge.py(file created)

@@ -0,0 +1,31 @@
1 + #!/usr/bin/env python3
2 + # A command tool that use PyPDF2 to merge pdf files
3 + # Usage: python3 pdf_merge.py -i file1.pdf,1-3 file2.pdf -o output.pdf
4 + # -i: input pdf file, followed by the page range to merge, the page range is separated by '-' and it is optional, if not provided, merge all pages
5 + # e.g. file1.pdf,1-3, merge page 1 to 3 of file1.pdf, file2.pdf, merge all pages of file2.pdf
6 + # -o: output pdf file
7 + # author: Ryan <ouyang.em@gmail.com>
8 +
9 + import argparse
10 + from PyPDF2 import PdfFileMerger
11 +
12 +
13 + def merge_pdf(input_files, output_file):
14 + merger = PdfFileMerger()
15 + for input_file in input_files:
16 + file_name, *page_range = input_file.split(',')
17 + if page_range:
18 + start, end = map(int, page_range[0].split('-'))
19 + merger.append(file_name, pages=(start - 1, end))
20 + else:
21 + merger.append(file_name)
22 + merger.write(output_file)
23 + merger.close()
24 +
25 +
26 + if __name__ == '__main__':
27 + parser = argparse.ArgumentParser(description='Merge PDF files')
28 + parser.add_argument('-i', '--input', nargs='+', help='Input PDF files')
29 + parser.add_argument('-o', '--output', help='Output PDF file')
30 + args = parser.parse_args()
31 + merge_pdf(args.input, args.output)
Newer Older