Click here to Skip to main content
15,887,417 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
This code is written in Python and I am retrieving PDF file stored in SQL Server table stored in varbinary data type code and I need to open this PDF file and be displayed in browser.

This code is working however it is creating output.pdf on local machine, which I don't want to get created.
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])
    f='output.pdf'
    with open(f,'wb') as outfile:
         outfile.write(row[1])
    webbrowser.open_new(f)


What I have tried:

It is creating a PDF file on the local machine. I want to create it in memory and not on local machine.
Posted
Updated 4-Oct-23 3:14am
v3
Comments
[no name] 3-Oct-23 16:33pm    
Putting the download in an "isolated storage" folder and reading / deleting it from there is effectively "in memory and not on local machine". You still need to deal with the "viewer"; which typically takes a "file".

1 solution

Your code is querying a database, retrieving a row, outputting the content of a field to a file, then pointing a web browser at that file.

To have a web browser open your PDF without saving it on the filesystem, you need to restructure your code to operate as an HTTP server. You will create an HTTP server instance, and wait for a connection from a client. Once you have that connection, you will query the database and output the PDF file binary data to the web client. This will require constructing an HTTP header with a Content-type: application/pdf. The header will be followed by an extra newline character, followed by the binary of the PDF file.

I think this link will give you the building blocks to do this. Python, create a Web (HTTP) server[^]

A valid HTTP response containing a PDF might look like:
HTTP/1.1 200 OK
Content-Type: application/pdf
Last-Modified: Thu, 10 Jul 2014 18:52:24 GMT
Accept-Ranges: bytes
ETag: "0e43616709ccf1:0"
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Sun, 29 Oct 2023 21:48:13 GMT
Content-Length: 1593751

%PDF-1.4
% 쏢
1 0 obj
<<
/Type /Catalog
/Outlines 3 0 R
/Pages 4 0 R
/Dests 5 0 R
/AcroForm 6 0 R
.. etc.
 
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