Skip to content

Commit fd50b62

Browse files
committed
Added utils append_pdf
1 parent 6cbddc0 commit fd50b62

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

CHANGES.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ Changelog
1212
[sgeulette]
1313
- Simplified `utils.convert_odt` and `utils.convert_file` parameters and returned value.
1414
[sgeulette]
15+
- Added utils `append_pdf`.
16+
[chris-adam]
1517

1618
3.46 (2026-01-15)
1719
-----------------

src/collective/documentgenerator/utils.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import logging
3131
import os
3232
import re
33+
import subprocess
3334
import tempfile
3435

3536

@@ -439,3 +440,40 @@ def get_subfiles(temp_file, nb_files):
439440
else:
440441
value = "".join(err)
441442
return code, value, nb_files
443+
444+
445+
def append_pdf(main_pdf_data, sub_pdf_data):
446+
"""Append sub_pdf_data pages to main_pdf_data using ghostscript.
447+
448+
:param main_pdf_data: bytes of the main PDF
449+
:param sub_pdf_data: bytes of the PDF to append
450+
:return: merged PDF bytes
451+
"""
452+
paths = []
453+
try:
454+
for data in (main_pdf_data, sub_pdf_data):
455+
fd, path = tempfile.mkstemp(suffix=".pdf")
456+
paths.append(path)
457+
os.write(fd, data)
458+
os.close(fd)
459+
fd, out_path = tempfile.mkstemp(suffix=".pdf")
460+
os.close(fd)
461+
paths.append(out_path)
462+
subprocess.check_call(
463+
[
464+
"gs",
465+
"-dBATCH",
466+
"-dNOPAUSE",
467+
"-q",
468+
"-sDEVICE=pdfwrite",
469+
"-sOutputFile={}".format(out_path),
470+
paths[0],
471+
paths[1],
472+
]
473+
)
474+
with open(out_path, "rb") as f:
475+
return f.read()
476+
finally:
477+
for path in paths:
478+
if os.path.exists(path):
479+
os.remove(path)

0 commit comments

Comments
 (0)