#!/usr/bin/env python3 """Merge the individual PDFs of each group into one file, then (optionally) delete the temp files. Usage: python3 -I merge_pdfs.py (run with the sandbox disabled when dest is outside the working dir) config.json = { "tmpDir": "/abs/tmp/dir", # where print_items.js wrote s{key}_{NN}_{label}.pdf "destDir": "/abs/destination/folder", # must already exist "prefix": "주석상법_제2편_", # final name = prefix + name + ".pdf" "groups": [["6", "제6장_중개업"], ["7", "제7장_위탁매매업"]], # [key, name] in the order wanted "deleteTmp": true # delete the temp PDFs after every group merged cleanly } A group with one file is copied. Page sums are compared with the merged file. Nothing is deleted unless every group merged with matching page counts and the number of merged inputs equals the number of files in tmpDir. """ import json import os import re import shutil import subprocess import sys cfg = json.load(open(sys.argv[1], encoding="utf-8")) T, D = cfg["tmpDir"], cfg["destDir"] def pages(p): out = subprocess.run(["pdfinfo", p], capture_output=True, text=True).stdout return int(re.search(r"Pages:\s+(\d+)", out).group(1)) all_files = [f for f in os.listdir(T) if f.endswith(".pdf")] used, ok = 0, True for key, name in cfg["groups"]: pat = re.compile(r"s%s_(\d{2,})_" % re.escape(key)) fs = sorted((f for f in all_files if pat.match(f)), key=lambda f: int(pat.match(f).group(1))) nums = [int(pat.match(f).group(1)) for f in fs] if nums != list(range(1, len(nums) + 1)): print("GAP in numbering for", key, nums[:10]); ok = False; continue paths = [os.path.join(T, f) for f in fs] out = os.path.join(D, cfg["prefix"] + name + ".pdf") if len(paths) == 1: shutil.copyfile(paths[0], out) else: subprocess.run(["pdfunite"] + paths + [out], check=True) s, m = sum(pages(p) for p in paths), pages(out) used += len(paths) flag = "OK" if s == m else "MISMATCH(inputs %d)" % s ok &= (s == m) print(f"{name} | {len(paths)}건 | {m}쪽 {flag}") if cfg.get("deleteTmp") and ok and used == len(all_files): for f in all_files: os.remove(os.path.join(T, f)) os.rmdir(T) print("temp deleted:", len(all_files), "files") else: print("temp NOT deleted (used %d of %d files, ok=%s)" % (used, len(all_files), ok))