Modyfing pdf and returning it as a django response
<p>I need to modify the existing pdf and return it as a response in Django. So far, I have found this solution to modify the file:</p>

<pre><code>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
</code></pre>

<p>It let's me download the pdf, but when I am trying to open it, I get the message, that the file is damaged or wasn't correctly decoded.</p>

<p>Does anyone know what am I don't wrong?</p>

<p>Thank you!</p>

<p>You can write the output PDF to the <code>response</code> object. So instead of this:</p>

<pre><code>response.write(output)
</code></pre>

<p>do this:</p>

<pre><code>output.write(response)
</code></pre>

<p>This will write the contents of the PDF to the response instead of the string version of the <code>output</code> object which would be something like:</p>

<pre><code>&lt;PyPDF2.pdf.PdfFileWriter object at 0x7f0e801ea090&gt;
</code></pre>

<p>which is what you will find in the downloaded PDF file.</p>

python django pdf