Streaming pdf in a browser

145 views
Skip to first unread message

lcham...@gmail.com

unread,
Sep 24, 2020, 10:54:53 AM9/24/20
to web2py-users
Hi,
i have a controller with this :
response.headers['Content-Disposition'] = 'inline; filename=%s' % request.vars.filename   

to force streaming the pdf file , and i do not why it does not work ..
any idea ?

Thank you 

 

Clemens

unread,
Sep 24, 2020, 11:10:05 AM9/24/20
to web2py-users
Have a try!

        response.title = 'Your Document Title'
   response.headers['Content-Type'] = 'application/pdf'
   response.headers['Content-Disposition']='inline'

   return response.stream(<location of PDF file to be streamed>)

I prefer the user to decide what to do (save or view in default browser) by
        response.title = 'Your Document Title'
   response.headers['Content-Type'] = 'application/pdf'
   response.headers['Content-Disposition']='attachment; filename={}.pdf'.format(request.vars.filename)

   return response.stream(<location of PDF file to be streamed>)

Best regards
Clemens

Laurent Chambon

unread,
Sep 24, 2020, 12:13:53 PM9/24/20
to web...@googlegroups.com
Thank you
note my controller has to return several data too
the page html displayed by this controllers displays pics , link to pdf ...
How can i do ? 
thank you

--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to a topic in the Google Groups "web2py-users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/web2py/F7nWHxb_6OI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to web2py+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/web2py/a5acb3fc-db71-4a9e-b94a-0ada13caf029n%40googlegroups.com.


--

Laurent Chambon
47 rue Pougnet
33400 Talence
06 64 13 71 16 
 

agent tresdev

unread,
Sep 24, 2020, 1:01:10 PM9/24/20
to web2py-users
You could show the pdf in a frame o open it a new tab (depends of the use case)

Laurent Chambon

unread,
Sep 25, 2020, 4:17:53 AM9/25/20
to web...@googlegroups.com
i have tried, no success

Alex Beskopilny

unread,
Sep 25, 2020, 4:44:58 AM9/25/20
to web2py-users
Hi!
solution

web2py func
 
def doc2user():
    import os
    prn_id = request.args(0,cast=int)
    task = db.zurina(prn_id) or error()
    qu=db.zurina.id == prn_id
    res= db(qu).select().first()
    upfolder= os.path.join(request.folder, 'docfiles')
    file_path = os.path.join( upfolder, res.new_image_file)
    ext = os.path.splitext( res.jenka_fnm  )
    with open(file_path, 'rb') as f:
            file_text= f.read()

    from gluon.contenttype import contenttype

    if len(ext) and len(ext[1]):
        response.headers['Content-Type'] = contenttype(ext[1])
    else:
        response.headers['Content-Type'] = contenttype('application/octet-stream')
    response.headers['Content-disposition'] = 'attachment; filename=\"%s"' % ( res.jenka_fnm)

    return file_text


четверг, 24 сентября 2020 г., 17:54:53 UTC+3 пользователь lcham...@gmail.com написал:

Alex Beskopilny

unread,
Sep 25, 2020, 5:30:04 AM9/25/20
to web2py-users
only pdf to browser - inline

def doc2user():
    import os
    prn_id = request.args(0,cast=int)
    task = db.zurina(prn_id) or error()
    qu=db.zurina.id == prn_id
    res= db(qu).select().first()
    upfolder= os.path.join(request.folder, 'docfiles')
    file_path = os.path.join( upfolder, res.new_image_file)
    ext = os.path.splitext( res.jenka_fnm  )
    with open(file_path, 'rb') as f:
            file_text= f.read()

    from gluon.contenttype import contenttype

    if len(ext) and len(ext[1]):
        response.headers['Content-Type'] = contenttype(ext[1])
    else:
        response.headers['Content-Type'] = contenttype('application/octet-stream')

    if len(ext) and len(ext[1]) and ext[1].endswith('pdf'):

          response.headers['Content-disposition'] = 'inline; filename=\"%s"' % ( res.jenka_fnm)
    else:

          response.headers['Content-disposition'] = 'attachment; filename=\"%s"' % ( res.jenka_fnm)



четверг, 24 сентября 2020 г., 17:54:53 UTC+3 пользователь lcham...@gmail.com написал:
Hi,

Laurent Chambon

unread,
Sep 28, 2020, 5:22:20 AM9/28/20
to web...@googlegroups.com
Thank you for your email, it does not work for me, coud you detail the use please


--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to a topic in the Google Groups "web2py-users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/web2py/F7nWHxb_6OI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to web2py+un...@googlegroups.com.

Alex Beskopilny

unread,
Sep 28, 2020, 7:43:33 AM9/28/20
to web2py-users

it's work with web2py
inline for pdf, jpeg, png ...
save file fot other file types

def doc2user():
  
    # read from db.table orig file name and path to file in upfolder
    import os
    prn_id = request.args(0,cast=int)
    task = db.zurina(prn_id) or error()
    qu=db.zurina.id == prn_id
    res= db(qu).select().first()
    upfolder= os.path.join(request.folder, 'docfiles')
  
    #  path to file content
    file_path = os.path.join( upfolder, res.new_image_file)
 
    # orig file name
    ext = os.path.splitext( res.jenka_fnm  )
    with open(file_path, 'rb') as f:
            file_text= f.read()

    from gluon.contenttype import contenttype
    tru_ext=''

    if len(ext) and len(ext[1]):
          tru_ext = ext[1].lower()

    if len(tru_ext) :
        response.headers['Content-Type'] = contenttype(tru_ext)

    else:
        response.headers['Content-Type'] = contenttype('application/octet-stream')

    if len(tru_ext) and  tru_ext.endswith(('pdf','jpeg', 'jpg', 'png', 'bmp')):

          response.headers['Content-disposition'] = 'inline; filename=\"%s"' % ( res.jenka_fnm)
    else:
          response.headers['Content-disposition'] = 'attachment; filename=\"%s"' % ( res.jenka_fnm)

   # some debug string, you can view it in browser
    #return "{}".format( file_path  )
    return file_text

Also, we need the quotes   'attachment; filename=\"%s"' % ( res.jenka_fnm)
                                                                                ^^^^^^^

четверг, 24 сентября 2020 г., 17:54:53 UTC+3 пользователь lcham...@gmail.com написал:
Hi,

Alex Beskopilny

unread,
Sep 28, 2020, 10:58:02 AM9/28/20
to web2py-users
1 create new app and mkdir docfiles in it

# models/db1.py
db.define_table( 'zurina',
                          Field('jenka_fnm', requires=IS_NOT_EMPTY(), label='orig_file_name'  ),
                          Field("fld",label="Remark", length=3500,),
                          Field('new_image_file', requires=IS_NOT_EMPTY(), label='w2p_file_name'  ),
                          )
# controllers/default.py

# -*- coding: utf-8 -*-

def error(message="auth ?!!!error!!!"):
    session.flash = message
    redirect(URL('index'))


def zurina():
    import os

    jenka_fnm=''
    l_id = 0

    new_image_file_path=''
    # mkdir docfiles in app dir !!!!!!!!!!!!!
    upfolder= os.path.join(request.folder, 'docfiles')

    form=SQLFORM.factory( Field('new_image_file', 'upload',uploadfolder= upfolder, requires=IS_NOT_EMPTY(),
                                        label='orig_file_name'  ),
                          Field("fld", 'text', label="Remark:", requires = IS_NOT_EMPTY(error_message='emplty field is bad!') ),
                          )

    form.element('textarea[name=fld]')['_rows']='2'


    if form.process().accepted:
          jenka_fnm = request.vars.new_image_file.filename # origin file name
          new_image_file_path = os.path.join(upfolder, form.vars.new_image_file)
          piece = dict( jenka_fnm = jenka_fnm, new_image_file = new_image_file_path  , fld = form.vars.fld  )
          l_id=db.zurina.insert(**db.zurina._filter_fields( piece  ))
          request.flash='Ok!!!'
          session.flash= 'ok! ok!'
          #redirect(URL('zurina_grid'))
    elif form.errors:
        response.flash = 'Please correct the error(s).'


    return locals()

def doc2user():

    import os
    prn_id = request.args(0,cast=int)
    task = db.zurina(prn_id) or error()
    qu=db.zurina.id == prn_id
    res= db(qu).select().first()
    file_path = res.new_image_file

    ext = os.path.splitext( res.jenka_fnm  )
    with open(file_path, 'rb') as f:
            file_text= f.read()

    from gluon.contenttype import contenttype
    tru_ext=''
    if len(ext) and len(ext[1]):
          tru_ext = ext[1].lower()

    if len(tru_ext) :
        response.headers['Content-Type'] = contenttype(tru_ext)
    else:
        response.headers['Content-Type'] = contenttype('application/octet-stream')

    if len(tru_ext) and  tru_ext.endswith(('pdf','jpeg', 'jpg', 'png', 'bmp')):
          response.headers['Content-disposition'] = 'inline; filename=\"%s"' % ( res.jenka_fnm)
    else:
          response.headers['Content-disposition'] = 'attachment; filename=\"%s"' % ( res.jenka_fnm)

    #return "{}".format( file_path  )
    return file_text

def zurina_grid():

      query = db.zurina.id > 0

      grid=SQLFORM.grid( query, maxtextlength=200,user_signature=False, csv=False, buttons_placement = 'left',
           orderby =~ db.zurina.id,

           links=[ lambda row: A('Save',_href=URL('doc2user',args=row.id),  _class="btn btn-default" , _title="save file to disk"  ), ],

           deletable = True, create=False, editable=False,showbuttontext=False)
      return locals()
-----------------------------------------------
# views/default/zurina.html
{{extend 'layout.html'}}

{{=A('Go to grid',_href=URL('zurina_grid'),_class="btn btn-primary btn-space", _title="View files list")}}

{{=form}}
# ---------- views/default/zurina_grid.html
{{extend 'layout.html'}}
{{=grid}}




четверг, 24 сентября 2020 г., 17:54:53 UTC+3 пользователь lcham...@gmail.com написал:
Hi,
Reply all
Reply to author
Forward
0 new messages