2016-09-23 2 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

두 가지 퍼즐 조각 - pdf 수정 및 응답 쓰기. 파트 작업을 수정합니까 (예 : 수정 된 pdf를 파일로 저장하려고 시도 했습니까)? – serg

답변

0

response 개체에 출력 PDF를 쓸 수 있습니다. 그래서이 대신 :

response.write(output) 

이 작업을 수행 :

:

output.write(response) 

이 대신 같은 것을 할 것 output 객체의 문자열 버전의 응답에 PDF의 내용을 작성합니다

<PyPDF2.pdf.PdfFileWriter object at 0x7f0e801ea090> 

다운로드 한 PDF 파일에서 찾을 수있는 내용입니다.

+0

효과가있었습니다! 고맙습니다! –

관련 문제