0leg
0leg

Reputation: 14144

How to create a PDF from a binary string?

There is a request has been made to the server using Python's requests module:

requests.get('myserver/pdf', headers)

It returned a status-200 response, which all contains PDF binary data in response.content

Question

How does one create a PDF file from the response.content?

Upvotes: 2

Views: 3637

Answers (1)

Edeki Okoh
Edeki Okoh

Reputation: 1844

You can create an empty pdf then save write to that pdf in binary like this:

from reportlab.pdfgen import canvas
import requests

# Example of path. This file has not been created yet but we 
# will use this as the location and name of the pdf in question

path_to_create_pdf_with_name_of_pdf = r'C:/User/Oleg/MyDownloadablePdf.pdf'

# Anything you used before making the request. Since you did not
# provide code I did not know what you used
.....
request = requests.get('myserver/pdf', headers)

#Actually creates the empty pdf that we will use to write the binary data to
pdf_file = canvas.Canvas(path_to_create_pdf_with_name_of_pdf)

#Open the empty pdf that we created above and write the binary data to. 
with open(path_to_create_pdf_with_name_of_pdf, 'wb') as f:
     f.write(request.content)
     f.close()

The reportlab.pdfgen allows you to make a new pdf by specifying the path you want to save the pdf in along with the name of the pdf using the canvas.Canvas method. As stated in my answer you need to provide the path to do this.

Once you have an empty pdf, you can open the pdf file as wb (write binary) and write the content of the pdf from the request to the file and close the file.

When using the path - ensure that the name is not the name of any existing files to ensure that you do not overwrite any existing files. As the comments show, if this name is the name of any other file then you risk overwriting the data. If you are doing this in a loop for example, you will need to specify the path with a new name at each iteration to ensure that you have a new pdf each time. But if it is a one-off thing then you do not run that risk so as long as it is not the name of another file.

Upvotes: 3

Related Questions