Modyfing pdf并将其作为django响应返回

时间:2016-09-23 23:00:59

标签: 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'] = '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,但是当我尝试打开它时,我收到消息,文件已损坏或未正确解码。

有谁知道我该怎么做?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以将输出PDF写入We were unable to review your app as it crashed on launch. We have attached detailed crash logs to help troubleshoot this issue. Next Steps Please revise your app and test it on a device while connected to an IPv6 network (all apps must support IPv6) to ensure it will launch without crashing. Resources For additional information about supporting IPv6 Networks, please refer to Supporting IPv6 DNS64/NAT64 Networks and Supporting IPv6-only Networks. For a networking overview, please see About Networking. 对象。所以不要这样:

response

这样做:

response.write(output)

这会将PDF的内容写入响应,而不是output.write(response) 对象的字符串版本,如下所示:

output

这是您在下载的PDF文件中找到的内容。