Click here to Skip to main content
15,886,963 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following code in Python:

Python
l_statement = "select srno,attachment from dbo.attachments where srno = 1"
   print(l_statement)
   sqlcursor.execute(l_statement)
   for row in sqlcursor.fetchall():
       print(type(row[1]))
       print(row[1])

       headers = {'Content-Disposition': 'inline; filename="out.pdf"'}
       #headers = {'Content-Disposition': 'attachment; filename="out.pdf"'}
       return Response(row[1], headers=headers, media_type='application/pdf')


When I run this program from FastAPI, I get the correct result for attachment. It gives me an option to Download file and I can download PDF file.

However, for inline option, it gives a message as:
Unrecognized response type; displaying content as text.

And shows as response in Response Body instead of opening PDF file in Browser:
%PDF-1.3
1 0 obj
<<
/Count 1
/Kids [3 0 R]
/MediaBox [0 0 595.28 841.89]
/Type /Pages
>>
endobj
2 0 obj
<<
/OpenAction [3 0 R /FitH null]
/PageLayout /OneColumn
/Pages 1 0 R
/Type /Catalog
>>
endobj
3 0 obj
<<
/Contents 4 0 R
/Parent 1 0 R
/Resources 6 0 R
/Type /Page
>>
endobj
4 0 obj
<<
/Filter /FlateDecode
/Length 74
>>
stream
x�3R��2�35W(�r
Q�w3T04�30PISp
	�Z(����)��(hx����+���(j*�d��#M
endstream
endobj
5 0 obj
<<
/BaseFont /Helvetica-Bold
/Encoding /WinAnsiEncoding
/Subtype /Type1
/Type /Font
>>
endobj
6 0 obj
<<
/Font <>
/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]
>>
endobj
7 0 obj
<<
/CreationDate (D:20230929150353Z15'03')
>>
endobj
xref
0 8
0000000000 65535 f 
0000000009 00000 n 
0000000096 00000 n 
0000000199 00000 n 
0000000279 00000 n 
0000000424 00000 n 
0000000526 00000 n 
0000000613 00000 n 
trailer
<<
/Size 8
/Root 2 0 R
/Info 7 0 R
/ID [<4527CC16A77C85F8369BA38DDA715212><4527CC16A77C85F8369BA38DDA715212>]
>>
startxref
674
%%EOF


What I have tried:

I have tried to create a PDF file in Python in memory and try to open in browser with Content-Disposition with Inline and attachment option.

It works for attachment but it does not work for inline.
Posted
Updated 4-Oct-23 3:13am
v2
Comments
Richard MacCutchan 4-Oct-23 4:16am    
The issue is obviously with the way that FastAPI deals with the call to the Response function. You should check the documentation to see if youare missing any options.

1 solution

Take a look at below exaple:

Python
files = {
'data' : data,
'document': open('file_name.pdf', 'rb')
}

headers = {
'Accept': "multipart/form-data",
'Content-Type': "application/pdf",
'Cache-Control': "no-cache",
}

r = requests.post(url, files=files, headers=headers)


More at: https://stackoverflow.com/questions/52945306/pdf-in-python-request[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900