I try to merge some pdfs with pypdf and I sadly new Document is an empty page... Any help is apreciated! Thanks in advance!
current_time = datetime.now().strftime("%m-%d-%Y_%H.%M")
obj_list = request.GET.getlist('PDFobj')
qs = CertificatePDF.objects.filter(id__in=obj_list)
pdfs = []
for pdf in qs:
path = pdf.location.path
pdfs.append(PdfReader(path))
merger = PdfMerger()
for pdf in pdfs:
merger.append(pdf)
temp = io.BytesIO()
merger.write(temp)
merger.close()
temp.seek(0)
fn = f'DocuName_{str(current_time)}.pdf'
return FileResponse(temp, as_attachment=True, filename=fn)
I tried with HttpResponse file/attachment also... without any sucess
I figured out that the BytesIO object has to be constructed as a file, and django is able to do this... it is really simple. Here the whole method if anyone needs this in the future:
from django.http import FileResponse
from django.core.files import File
import io
from pypdf import PdfMerger, PdfReader
from datetime import datetime
def download_pdf_multiple(request):
current_time = datetime.now().strftime("%Y-%m-%d_%H-%M")
obj_list = request.GET.getlist('PDFobj')
qs = CertificatePDF.objects.filter(id__in=obj_list)
pdfs = []
for pdf in qs:
path = pdf.location.path
pdfs.append(PdfReader(path))
merger = PdfMerger()
for pdf in pdfs:
merger.append(pdf)
temp = io.BytesIO()
merger.write(temp)
merger.close()
temp.seek(0)
fn = f'DocuName_{str(current_time)}.pdf'
new_pdf = File(temp)
return FileResponse(new_pdf, as_attachment=True, filename=fn)