无法使用Django下载pdf

时间:2020-01-11 14:31:31

标签: django reactjs pdf download reportlab

我想要在我的Django / React应用程序中“ Generate Pdf”功能将JSON转换为PDF。我的整个应用程序都在工作,有很多请求,响应,但是以某种方式我尝试了许多解决方案,并且生成的pdf无法下载。

来自React的请求

    generatePdf() {
    return fetch(APP_URL + '/generate_pdf/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `JWT ${localStorage.getItem('token')}`,
        },
        body: JSON.stringify(this.data)
    }).then((response) => {
        if (!response.ok) throw new Error(response.status);
        else return response;
    })
}

Django视图(来自示例https://docs.djangoproject.com/en/3.0/howto/outputting-pdf/):

class PdfSongView(generics.UpdateAPIView, HTMLMixin):

def post(self, request, *args, **kwargs):
    """
    Generates pdf from context data and updates pdf path for given song
    """
    # Create a file-like buffer to receive PDF data.
    buffer = io.BytesIO()

    # Create the PDF object, using the buffer as its "file."
    p = canvas.Canvas(buffer)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(100, 100, "Hello world.")

    # Close the PDF object cleanly, and we're done.
    p.showPage()
    p.save()

    # FileResponse sets the Content-Disposition header so that browsers

请求后,我得到: [11 / Jan / 2020 15:22:48]“ POST / generate_pdf / HTTP / 1.1” 200 1413

在浏览器/网络/ generate_pdf /响应中,我有:

%PDF-1.3
% ReportLab Generated PDF document http://www.reportlab.com
1 0 obj
<<
/F1 2 0 R
>>
endobj
2 0 obj
<<
/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
>>
endobj
3 0 obj
<<
/Contents 7 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 6 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<

>> 
  /Type /Page
>>
endobj
4 0 obj
<<
/PageMode /UseNone /Pages 6 0 R /Type /Catalog
>>
endobj
5 0 obj
<<
/Author (anonymous) /CreationDate (D:20200111152248-01'00') /Creator (ReportLab PDF Library - www.reportlab.com) /Keywords () /ModDate (D:20200111152248-01'00') /Producer (ReportLab PDF Library - www.reportlab.com) 
  /Subject (unspecified) /Title (untitled) /Trapped /False
>>
endobj
6 0 obj
<<
/Count 1 /Kids [ 3 0 R ] /Type /Pages
>>
endobj
7 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 101
>>
stream
GapQh0E=F,0U\H3T\pNYT^QKk?tc>IP,;W#U1^23ihPEM_?CW4KISi90EC-p>QkRte=<%VL%>/9S.n+\Kodj>&1ruY"YKd-rtBM~>endstream
endobj
xref
0 8
0000000000 65535 f 
0000000073 00000 n 
0000000104 00000 n 
0000000211 00000 n 
0000000414 00000 n 
0000000482 00000 n 
0000000778 00000 n 
0000000837 00000 n 
trailer
<<
/ID 
[<e61f2c0f0cc99a5348a079512dda3077><e61f2c0f0cc99a5348a079512dda3077>]
% ReportLab generated PDF document -- digest (http://www.reportlab.com)

/Info 5 0 R
/Root 4 0 R
/Size 8
>>
startxref
1028
%%EOF

但是没有下载文件,也没有打开pdf。

其他一些也不起作用的解决方案:

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="WishList.pdf"'
        from reportlab.pdfgen import canvas
        buffer = io.BytesIO()
        p = canvas.Canvas(buffer)
        p.drawString(100, 100, "Hello world.")
        p.showPage()
        p.save()
        pdf = buffer.getvalue()
        # buffer.close()
        # response.write(pdf)

        response = FileResponse(buffer, as_attachment=True, filename='hello.pdf', content_type='application/pdf')
        # set the content length to let the browser know how many bytes to expect
        response['Content-Length'] = buffer.getbuffer().nbytes
        return response
        with open('simple_demo.pdf', 'rb') as pdf:
            response = HttpResponse(pdf.read(), content_type='application/pdf')
            response['Content-Disposition'] = 'filename=some_file.pdf'
            return response

        try:
            return HttpResponse(open('simple_demo.pdf', 'rb'), content_type='application/pdf')
        except FileNotFoundError:

另一个解决方案生成了文件,但是我无法通过FileResponse或open函数来提供文件。 我想知道设置中的某些参数是否正在阻止过程或浏览器/标题/反应。 在Chrome和Edge中试用过。

0 个答案:

没有答案