Lash
Lash

Reputation: 353

Set in memory image in PDF with Flask

I am just trying to draw an image to a pdf. This image is loaded from my mongodb database through an API. I tried this solution but it raises the following error:

2022-09-14T21:05:56.561767+00:00 app[web.1]: remote_file = ImageReader(urlopen(img_url)).read()
2022-09-14T21:05:56.561767+00:00 app[web.1]: AttributeError: 'ImageReader' object has no attribute 'read'

Also, if you know a better way to set this image in the pdf let me know please. This is the code I am using:

  def get(self, usermail, dog_name):

      client = pymongo.MongoClient('mongodb://uri')
      filter={'UserMail':usermail,'title':dog_name}
      

      result = client['db']['Todo'].find(
        filter=filter
      )

      json_response = json.dumps(list(result), default=json_util.default)
      dog = json.loads(json_response)
      df = pd.DataFrame(dog).to_dict()
      dog_img = df['DogImg'][0]
      img_url = 'https://url' + dog_img 
 
      dog_age = df['Age'][0]
      dog_desc = df['DogDescription'][0]
      dog_name = df['title'][0]
      dog_breed = df['Breed'][0]

      buf = io.BytesIO()
      c = canvas.Canvas(buf, pagesize=letter)
      #c.drawImage(logo, 30, 700, width=50, height=50)
      c.setFont("Helvetica", 20)
      c.drawString(100, 720, dog_name)
      buf.seek(0)

      remote_file = ImageReader(urlopen(img_url)).read()
      memory_file = io.BytesIO(remote_file)
      buf.seek(0)
      new_pdf = PdfFileReader(buf)
      existing_pdf = PdfFileReader(memory_file) 
      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')

Upvotes: 0

Views: 32

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 880

Try using the following

from reportlab.platypus import Image, SimpleDocTemplate
from flask import send_file

pdf_filename = 'original.pdf'
new_filename = "new_filename.pdf"

pdf_template = SimpleDocTemplate(pdf_filename, pagesize=letter,topMargin=0, bottomMargin=0, leftMargin=0, rightMargin=0)
story1 = []

img_url = 'https://url' + dog_img
# or from locally in project
# img_url  = os.path.join(cwd, "dog_img")

img1 = Image(img_url, width=600, height=780)
story1.append(img1)
pdf_template.build(story1)

return send_file(pdf_filename, attachment_filename=new_filename, as_attachment=True)

Upvotes: 1

Related Questions