2016-09-23 43 views
0

我需要修改現有的pdf並將其作爲Django響應返回。到目前爲止,我發現這個解決方案修改文件:Modyfing 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

有2個拼圖 - 修改pdf並寫入響應。修改部分工作(例如,您是否嘗試將修改過的pdf保存爲文件)? – serg

回答

0

您可以將輸出PDF寫入response對象。因此,而不是這樣的:

response.write(output) 

做到這一點:

output.write(response) 

這將PDF的內容寫入響應,而不是output對象的字符串版本,這將是這樣的:

<PyPDF2.pdf.PdfFileWriter object at 0x7f0e801ea090> 

這就是你會在下載的PDF文件中找到的。

+0

它的工作!謝謝! –

相關問題