1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- import config
- from PyPDF2 import PdfMerger
- from pathlib import Path
- import re
- import json
- from datetime import datetime
- def pdf_merge(base_dir: str, report_name, config=None):
- if config is None:
- config = {"_0": []}
- report_prefix = re.sub(r"\[([^\]]+)\]", "", report_name)
- if report_prefix[-2:] == "__":
- report_prefix = report_prefix[:-1]
- for suffix, entries in config.items():
- target = f"{base_dir}/{report_prefix}{suffix}.pdf"
- if Path(target).exists():
- Path(target).unlink()
- pdfs = [f for f in Path(base_dir).glob(report_prefix + "*.pdf")]
- pdfs.sort(key=lambda f: f.stat().st_mtime)
- if len(entries) > 0:
- pdfs = [f for e in entries for f in pdfs if e + ".pdf" in f.name]
- if len(pdfs) > 0:
- with PdfMerger() as merger:
- for pdf in pdfs:
- merger.append(pdf)
- merger.write(target)
- def pdf_merge_files(file_dict: dict[str, list[str]]):
- max_age = datetime.now().timestamp() - 12 * 60 * 60
- for target, file_list in file_dict.items():
- if target[-4:] != ".pdf":
- continue
- pdfs = [
- f
- for f in file_list
- if Path(f).exists() and Path(f).stat().st_mtime > max_age
- ]
- if len(pdfs) == 0:
- continue
- try:
- with PdfMerger() as merger:
- for pdf in pdfs:
- merger.append(pdf)
- merger.write(target)
- except PermissionError:
- print(target)
- print("--> not accessible!")
- def get_reports(reports_file, folder):
- with open(reports_file, "r") as frh:
- reports = json.load(frh)
- return [r["name"] for r in reports if r["path"].startswith(folder)]
- def merge_reports_in_folder(
- cfg: config.Config, folder="Team Content/ReportOutput", config=None
- ):
- reports = get_reports(cfg.cognos11.reports_file, folder)
- print(folder)
- folder2 = folder[26:]
- for r in reports:
- print(folder2 + "/" + r)
- pdf_merge(cfg.cognos11.reportoutput_dir + "/" + folder2, r, config)
- def get_config_json(config, config_dir):
- if config == "":
- return None
- if config.startswith("{"):
- return json.loads(config)
- config_file = f"{config_dir}/merge/{config}.json"
- if not Path(config_file).exists():
- return None
- with open(config_file, "r") as frh:
- return json.load(frh)
- if __name__ == "__main__":
- merge_reports_in_folder(config.Config())
|