Python 修改pdf并将其作为django响应返回
我需要修改现有的pdf并将其作为Django中的响应返回。到目前为止,我已找到此解决方案来修改文件:Python 修改pdf并将其作为django响应返回,python,django,pdf,Python,Django,Pdf,我需要修改现有的pdf并将其作为Django中的响应返回。到目前为止,我已找到此解决方案来修改文件: def some_view(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attac
def some_view(request):
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment;filename="somefilename.pdf"'
packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
##################### 1. First and last name
first_last_name = "Barney Stinson"
can.drawString(63, 686, first_last_name)
#Saving
can.save()
#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file("fw9.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
#outputStream = file("output.pdf", "wb")
#output.write(outputStream)
response.write(output)
outputStream.close()
return response
它让我下载pdf,但当我试图打开它,我得到的信息,该文件已损坏或未正确解码
有人知道我错了吗
谢谢大家! 您可以将输出PDF写入响应对象。因此,与此相反:
response.write(output)
这样做:
output.write(response)
这将把PDF的内容写入响应,而不是输出对象的字符串版本,如下所示:
<PyPDF2.pdf.PdfFileWriter object at 0x7f0e801ea090>
这就是您将在下载的PDF文件中找到的内容。有两个难题-修改PDF并将其写入响应。修改零件工作例如,您是否尝试过将修改后的pdf保存为文件?