How can I generate a PDF file directly from byte data in Python without having to write it to a binary file first?

This Python code retrieves data from a database table and converts it into a PDF file without saving it to disk, then displays it in the browser.

  1. l_statement = "select srno,attachment from dbo.attachments where srno = 1"
  2. sqlcursor.execute(l_statement)
  3. for row in sqlcursor.fetchall():
  4.    print(type(row[1]))
    
  5.    print(row[1])
    
  6.    '''f='output.pdf'
    
  7.    with open(f,'wb') as outfile:
    
  8.         outfile.write(row[1])'''
    
  9. webbrowser.open_new(pdf)

Data Type of Output:

<class 'bytes'> b"%PDF-1.3\n1 0 obj\n<<\n/Count 1\n/Kids [3 0 R]\n/MediaBox [0 0 595.28 841.89]\n/Type /Pages\n>>\nendobj\n2 0 obj\n<<\n/OpenAction [3 0 R /FitH null]\n/PageLayout /OneColumn\n/Pages 1 0 R\n/Type /Catalog\n>>\nendobj\n3 0 obj\n<<\n/Contents 4 0 R\n/Parent 1 0 R\n/Resources 6 0 R\n/Type /Page\n>>\nendobj\n4 0 obj\n<<\n/Filter /FlateDecode\n/Length 74\n>>\nstream\nx\x9c3R\xf0\xe22\xd035W(\xe7r\nQ\xd0w3T04\xd330P\x08ISp\r\x01\t\x19\x1b\xea\x19Z(\x98\x9b\x99\xe9\x19\x19)\x84\xa4(hx\xa4\xe6\xe4\xe4+\x84\xe7\x17\xe5\xa4(j*\x84d\x81\xd4\x01\x00\x16#\x10M\nendstream\nendobj\n5 0 obj\n<<\n/BaseFont /Helvetica-Bold\n/Encoding /WinAnsiEncoding\n/Subtype /Type1\n/Type /Font\n>>\nendobj\n6 0 obj\n<<\n/Font <</F1 5 0 R>>\n/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]\n>>\nendobj\n7 0 obj\n<<\n/CreationDate (D:20230929150353Z15'03')\n>>\nendobj\nxref\n0 8\n0000000000 65535 f \n0000000009 00000 n \n0000000096 00000 n \n0000000199 00000 n \n0000000279 00000 n \n0000000424 00000 n \n0000000526 00000 n \n0000000613 00000 n \ntrailer\n<<\n/Size 8\n/Root 2 0 R\n/Info 7 0 R\n/ID [<4527CC16A77C85F8369BA38DDA715212><4527CC16A77C85F8369BA38DDA715212>]\n>>\nstartxref\n674\n%%EOF\n"

Answer №1

l_query = "select ID, file from dbo.documents where ID = 1" print(l_query) database_cursor.execute(l_query)
for data_row in database_cursor.fetchall(): download_headers = {'Content-Disposition': 'attachment; filename="out.pdf"'} return Response(data_row[1], headers=download_headers, media_type='application/pdf')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An error has occurred as the Chrome binary could not be located. Please raise the exception class with the message, screen, and stack trace to resolve this issue

Using the selenium library, we can control web browsers programmatically. In this code snippet, we first import the necessary modules using statements like from selenium.webdriver.common.keys import Keys. We also set a variable called "PATH" to store the ...

Divide the strings using punctuation marks, but leave the tags intact

How can I split a string by removing all punctuation marks and spaces, except for the # character? tweet = "I visited #India to experience the culture. It was amazing!" I want to separate the words in the string above like this: ["I", "visited", "#India ...

The issue with Python Selenium driver.get() function not functioning properly when used within a for loop

Here is some code that logs into a YouTube account and then visits a few YouTube videos. The problem arises in the following scenarios: If I use a direct link like this, it works fine driver.get('https://www.youtube.com/watch?v=FFDDN1C1MEQ') ...

I am encountering difficulty using Selenium to interact with the dropdown link on my UI

I have been working on a selenium test case in python for a UI that resembles the following: https://i.stack.imgur.com/Q6Hvl.png My goal is to click on the drop-down button highlighted in red, with the xpath value: //div[contains(text(), 'Interface S ...

What could be the reason for scrapy not returning any URLs?

Recently, I attempted to develop a tool to simplify my apartment search and access relevant information quickly (the website is not very user-friendly). However, I have encountered an issue and I may be overlooking something obvious...or perhaps I'm j ...

Python (Selenium) - Guide on extracting and storing data from multiple pages into a single CSV file

I am facing a challenge with scraping data from a web page that contains a table spanning multiple pages. I am using Python with selenium for this task. The website in question is: The issue I am encountering is related to navigating through the pages of ...

Using regular expressions in Python to compare C++ strings and string literals

Currently, I am attempting to identify Strings (enclosed by both double and single quotes) as well as String Literals within C++ source files. To accomplish this task, I am utilizing the re library in Python. I have successfully managed to match double qu ...

An error is thrown when Django tries to pass a variable to Httpresponseredirect

I am currently experiencing an issue where I receive the following error: Reverse for 'documentation' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] whenever I attempt to redirect to anoth ...

How to extract text from HTML body using Python with Selenium without the tags?

Can anyone help me extract a specific sentence using Selenium and Python? <h2 id='PO-PF2' class="section">Program Information</h2> Length: Two-year Ontario College Graduate Certificate program <br />Delivery Sequence:<br /&g ...

Python's ability to nest objects within other objects allows for complex data

I had an interesting experience during a quiz in my class. One of the questions stated that an object in Python cannot contain other objects within itself, which didn't quite add up to me. After all, why couldn't there be a class table and a clas ...

The response from $http.get is not defined

Currently, I am working on the front end of a project using HTML, while utilizing Python for the back end. To handle communication between the two, I have integrated AngularJS. The challenge I am currently encountering pertains to retrieving responses fro ...

Opening a Webpage with Logged-in Status Using Python and Selenium

I've seen similar questions asked about this topic, but I have checked numerous posts and still can't figure it out. My goal is to launch a webpage using my existing Chrome profile/user data so that I don't have to log in again. Ideally, I w ...

What are some types of webpage elements that change and move?

Is it possible to effectively interact with elements on websites that utilize dynamically changing classes or IDs, updating during runtime and upon page refresh, through the use of Selenium in Python? I am unfamiliar with this particular situation as I ha ...

Create a Jacobian matrix using Python without relying on existing libraries

Currently, I am working on creating the derivative matrix of the softmax function, also known as the Jacobian matrix of Softmax. In mathematical terms, the derivative of Softmax(Xi) with respect to Xj can be expressed as: https://i.stack.imgur.com/tY3os. ...

Using Python to Determine MariaDB Connection Status

Is there a method in the MariaDB connector for Python that checks the connection state, similar to is_connected in python-mysql? Or is there another way to determine the connection status? ...

Is it recommended to utilize either a single or multiple instances of Python's secrets.SystemRandom() class?

When it comes to generating random numbers securely, I stumbled upon the secrets module which seems to be the go-to solution. However, I have a question - should I create one or multiple instances of the secrets.SystemRandom class for generating 17 random ...

Using a "while" loop, eliminate items from one list that are present in another list

I have developed a basic program that removes elements from one list when they are present in another list using the in method at least twice: def remove(l_list,s_list): """Remove items from s_list in l_list and return the remaining items""" res=[ ...

What are the steps to start running the while loop?

To provide more clarity: I am developing an intersection control system for cars where each car must register its address in a shared list (intersectionList) if it intends to cross the intersection. If cars are on road piece 20 or 23, they add their addre ...

The Django annotate function does not support accessing a floatfield within a model

I am attempting to add annotations to a queryset with the distances between each object and a location provided by the user. This is what I have implemented so far: lat1 = request.POST['lat'] lon1 = request.POST['lon'] locations = Loc ...

ìdentifying Incomplete JSON Data using Python

I'm currently working on an innovative online weather web application. The goal of this app is to allow users to search for any city or town and instantly receive accurate weather statistics. However, I have encountered a hurdle in my project. The fre ...