我正在尝试将 Django 中的两个 pdf 文件与 PyPDF2 和 ReportLab 合并。我的看法如下:
@login_required
def export_to_pdf(request, user_id):
member = Member.objects.filter(user_id=user_id).values('user_id',
'user__first_name',
'user__last_name',
'company_name',
'vat_number',
'address',
'postcode',
'city',
'user__email',
'telephone',
'subscription__type__name',
'subscription__type__limit',
).annotate(num_calculations=Count('user__calculations'))[0]
company_address = "{}, {} {}".format(member['address'], member['postcode'], member['city'])
buffer = BytesIO()
# Create the PDF object, using the BytesIO object as its "file."
p = canvas.Canvas(buffer, pagesize=A4)
p.setFont('Helvetica-Bold', 8)
p.drawString(70, 765, "{}".format(member['company_name']))
p.drawString(70, 731, "{}".format(company_address))
p.drawString(70, 714, "{}".format(member['telephone']))
p.drawString(335, 697, "{}".format(member['vat_number']))
p.drawString(335, 697, "{}".format(member['vat_number']))
p.save()
buffer.seek(0)
new_pdf = PdfFileReader(buffer)
existing_pdf = PdfFileReader(open('master/files/file.pdf', "rb"))
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output = PdfFileWriter()
output.addPage(page)
output_stream = open("master/files/new_file.pdf", "wb")
output.write(output_stream)
output_stream.close()
with open('master/files/new_file.pdf', 'r', encoding="Latin-1") as pdf:
response = HttpResponse(pdf.read(), content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=some_file.pdf'
return response
项目树如下:
因此,我创建新文件,然后打开现有文件file.pdf
,然后合并这两个文件。最后,我为 output 创建了一个文件new_file.pdf
。
这工作正常,但问题在于返回的文件。如果我运行export_to_pdf
函数,我应该得到new_file.pdf
. 我得到了那个文件,但那个文件的内容只是我创建的
p = canvas.Canvas(buffer, pagesize=A4)
p.setFont('Helvetica-Bold', 8)
p.drawString(70, 765, "{}".format(member['company_name']))
p.drawString(70, 731, "{}".format(company_address))
p.drawString(70, 714, "{}".format(member['telephone']))
p.drawString(335, 697, "{}".format(member['vat_number']))
p.drawString(335, 697, "{}".format(member['vat_number']))
p.save()
没有合并文件的内容file.pdf
。
但是,如果我new_file.pdf
通过单击直接打开它,我会得到应有的一切。
任何建议我做错了什么?