Search code examples
pythonflaskweasyprint

How to use WeasyPrint PDF Builder on Password Protected Pages?


I'm trying to download a page from my Flask app using WeasyPrint but when downloading the PDF, I'm getting the login page as the PDF rather than the expected page.

I'm using the following code:

@app.route('/report.pdf')
def hello_pdf():
    # Make a PDF from another view
    return render_pdf(url_for('myprojects'))

The login decorator is:

def login_required(f):
    '''login required decorator to protect routes
    '''
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            flash('You need to login first.')
            return redirect(url_for('login'))
    return wrap

For some reason, the function can't seem to download the protected view, despite me being logged in. How can I get it to download it correctly?


Solution

  • Turns out render_template just returns a html string, so I can do the following at the end of a route:

    html = render_template('myprojects.html', projects=projects)
    return render_pdf(HTML(string=html))