Я хочу в своем приложении Django / React функцию «Создать 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 view ( из примера 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 / response у меня есть:
%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.