import tempfile import subprocess import os.path def extract_pages(source, bookmark, start=None, end=None): return extract_and_concat([(source, bookmark, start, end)]) def extract_and_concat(items): # create a temporary directory for our sections d = tempfile.TemporaryDirectory(prefix="polyphonic_") sections = [] for i, (source, bookmark, start, end) in enumerate(items): if start is None: sections.append(source) else: if end is None: end = start dest = os.path.join(d.name, f'section_{i}.pdf') cmd = ['gs', '-sDEVICE=pdfwrite', '-q', '-dBATCH', '-dNOPAUSE', f'-dFirstPage={start}', f'-dLastPage={end}', f'-sOutputFile={dest}', source] subprocess.run(cmd, check=True) sections.append(dest) # concat the items output = tempfile.NamedTemporaryFile(prefix="polyphonic_", suffix='.pdf') cmd = ['gs', '-sDEVICE=pdfwrite', '-q', '-dBATCH', '-dNOPAUSE', '-sOutputFile=-'] cmd.extend(sections) subprocess.run(cmd, stdout=output) output.seek(0) return output