Reportlab add image to pdf

4,094 views
Skip to first unread message

Winter Kryz

unread,
Mar 18, 2016, 12:28:24 AM3/18/16
to web2py-users
Hello everyone,
I am trying to generate reports using Reportlab in web2py. I'm working on pythonanywhere.com
I am having some problems because I want to insert an image as header into the pdf report

this is my report.py

from reportlab.platypus import *
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import inch, mm
from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY
from reportlab.platypus import SimpleDocTemplate, Image
from reportlab.lib import colors
from uuid import uuid4
from cgi import escape
import os

def index():
    title = "Mi mundo REPORTE PDF"
    heading = "MI PRIMER RE"
    text = 'bla '* 10
    styles = getSampleStyleSheet()
    tmpfilename=os.path.join(request.folder,'private',str(uuid4()))
    doc = SimpleDocTemplate(tmpfilename)
    story = []
    logo = "/static/images/logounca.png"
    imagen_logo = Image(os.path.realpath(logo),width=400,height=100)
    story.append(imagen_logo)
    story.append(Paragraph(escape(title),styles["Title"]))
    story.append(Paragraph(escape(heading),styles["Heading2"]))
    story.append(Paragraph(escape(text),styles["Normal"]))
    story.append(Spacer(1,2*inch))
    doc.build(story)
    data = open(tmpfilename,"rb").read()
    os.unlink(tmpfilename)
    response.headers['Content-Type']='application/pdf'
    return data

My view.html
{{extend 'layout.html'}}
<h1>This is my report/index.html</h1>
{{=BEAUTIFY(response._vars)}}

When I try to view the pdf, it gives me this error

<type 'exceptions.IOError'> Cannot open resource "/static/images/logounca.png" fileName='/static/images/logounca.png' identity=[ImageReader@0x7fa7f0bf5510 filename='/static/images/logounca.png']


I don't know if I am calling the image url wrong or If I uploaded the image wrongly.
I uploaded the image on pythonanywhere.com through the Static section.
If someone can help me with this issue, please

Thanks :)

Nico de Groot

unread,
Mar 18, 2016, 3:26:09 AM3/18/16
to web2py-users
You use realpath as if it construct a path to your image file. But you should use os.path.join as you did earlier. If you've used web2py upload facilities, you need an extra step to get the file from the upload folder, see the web2py book for details.

Nico de Groot

Winter Kryz

unread,
Mar 18, 2016, 8:53:11 PM3/18/16
to web2py-users
I tried the os.path.join but didn't work. Can someone help me with this, please?

Edwood

unread,
Mar 18, 2016, 10:59:40 PM3/18/16
to web...@googlegroups.com


The error message suggests the script cannot find the image in that folder.  Using pyFPDF this is how I would build the path using "os.path.join":

 os.path.join(request.folder,'static/images', 'logounca.png')
Reply all
Reply to author
Forward
0 new messages