Created
September 13, 2023 10:09
-
-
Save luochen1990/48e83a9941987324e11c4310dc05b2f1 to your computer and use it in GitHub Desktop.
合并多个 pdf 文件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env nix-shell | |
#!nix-shell -i python --packages python311 python311Packages.pypdf2 | |
import PyPDF2 | |
def merge_pdfs(input_path_list: list[str], output_path: str): | |
pdfWriter = PyPDF2.PdfWriter() | |
for input_path in input_path_list: | |
pdf1 = PyPDF2.PdfReader(open(input_path, "rb")) | |
for page in pdf1.pages: | |
pdfWriter.add_page(page) | |
with open(output_path, "wb") as f: | |
pdfWriter.write(f) | |
if __name__ == "__main__": | |
import sys | |
import os | |
nargs = len(sys.argv) | |
if nargs <= 3: | |
print("Usage: {input_pdf_path_1} {input_pdf_path_2} ... {output_pdf_path}") | |
exit(1) | |
input_num = nargs - 2 | |
input_paths = sys.argv[1:input_num+1] | |
for input_path in input_paths: | |
if not os.path.exists(input_path): | |
print("Failed! input file not found:", input_path) | |
exit(1) | |
output_path = sys.argv[-1] | |
if os.path.exists(output_path): | |
print("Failed! output file already exists:", output_path) | |
exit(1) | |
print("Merging: ", input_paths) | |
merge_pdfs(input_paths, output_path) | |
print("Success: ", output_path) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment