Return pdf response without storing it locally in Python and PyPDF2

Viewed 32

How can I return a pdf in memory response? I just want to display it in my browser directly without storing it locally. I am opening a pdf stored in a server and opening it with PyPDF2 package.

Here is my code where I used the package io to write in bytes my custom pdf. So far my api returns a null response.

def write_dog_pdf(title):


  packet = io.BytesIO()
  can = canvas.Canvas(packet, pagesize=letter)

  first_col_size = 575
  first_col_width = 140
  sec_col_width = 240

  can.setFillColorRGB(1, 0, 0)
  can.setFont("Times-Roman", 12)
  can.drawString(first_col_width, first_col_size, title) #title

  remote_file = urlopen(Request('https://some_url...')).read()
  memory_file = io.BytesIO(remote_file)

  packet.seek(0)
  new_pdf = PdfFileReader(packet)
  existing_pdf = PdfFileReader(memory_file) #PdfFileReader(open("contratoadopcion.pdf", "rb"))
  pdf = PdfFileWriter()
  page = existing_pdf.getPage(0)
  page.mergePage(new_pdf.getPage(0))
  pdf.addPage(page)
  outputStream = open("destination.pdf", "wb")
  pdf.write(outputStream)
  outfile = io.BytesIO()
  pdf.write(outfile)
  outfile.seek(0)

  return send_file(outfile, mimetype='application/pdf',attachment_filename='output.pdf')
0 Answers
Related