Search code examples
pythondjangobyte

How to Merge Byte Files Together in Python


I am running into a situation where I need to generate multiple filled PDF forms, I have the data filled out and the 'bytes' file is accessible, but when I attempt to combine the 2 files in their byte representation, nothing happens, the file is overridden and the original is the only thing shown.

What am I doing wrong, this seems like it should be easy.

# don't worry about these, they are filled PDFs in byte form, this works as expected.
pdf1 = PDFFormManager.fill_with_jinja(file=template, data=data)
pdf2 = PDFFormManager.fill_with_jinja(file=template, data={})
# here is the issue
print(len(pdf1), len(pdf2))     # 177354 177354
print(type(pdf1), type(pdf2))   # <class 'bytes'> <class 'bytes'>
print(len(pdf1+ pdf2))          # 354708
# when I return this, I only get the single pdf, not the concatenated one
response = HttpResponse(pdf1+pdf2, content_type=f"application/pdf")

Solution

  • The solution was to take a step back and use pypdf to merge the content from the writer object.

    For example:

    pdf = PDFFormManager.fill_with_jinja(file=template, data=data)
    
    pdf_merged_buffer = BytesIO()
    
    merger = PdfMerger()
    # merger.append(pdf)
    merger.append(PdfReader(io.BytesIO(pdf)))
    merger.append(PdfReader(io.BytesIO(pdf)))
    merger.write(pdf_merged_buffer)   # now shows all pages combined!
    
    response = HttpResponse(pdf_merged_buffer.getvalue(), content_type=f"application/pdf")
    response['Content-Disposition'] = 'inline; filename="{}"'.format('file.pdf')
    response['Content-Length'] = len(response.content)