from flask import Flask, render_template, Response, abort, url_for # from weasyprint import HTML import os from pagedjs import make_pdf_from_url from settings import BASEURL, DEBUG, HTML_TMP_DIR, SITEURL import tempfile from werkzeug.security import safe_join app = Flask(__name__) """ Shows the index page of the application """ @app.route('{}/'.format(BASEURL)) def index(): context = {} return render_template('index.html', **context) """ This is where the book generation happens. Possibly adjust the allowed methods. """ @app.route('{}/generate'.format(BASEURL), methods=['GET', 'POST']) def generate (): context = { 'DEBUG': DEBUG } html = render_template('book.html', **context) if (DEBUG): return html else: pdf = make_pdf(html) r = Response(pdf, mimetype='application/pdf') r.headers.extend({ 'Content-Disposition': 'attachment; filename="Title of the.pdf"' }) return r """ Proxy(?) for pagedjs, it stores the provided html in a separate file. Now pagedjs can connect to the application through HTTP. This way static files, like fonts, images and css can be served in a regular way. """ def make_pdf (html): if not os.path.exists(HTML_TMP_DIR): os.mkdir(HTML_TMP_DIR) with tempfile.NamedTemporaryFile(mode='w', prefix='book_', dir=HTML_TMP_DIR, delete=False) as tmpfile: tmpfile.write(html) tmpfile.flush() bookname = os.path.basename(tmpfile.name) url = SITEURL + url_for('show_book', bookname=bookname) tmpfile.close() # Generate the pdf with pagedjs return make_pdf_from_url(url) """ View for pagedjs. It loads the generated HTML from the tmp dir and returns it. """ @app.route('{}/book/'.format(BASEURL)) def show_book (bookname): bookpath = safe_join(HTML_TMP_DIR, bookname) if os.path.exists(bookpath): with open(bookpath, 'r') as h: html = h.read() return html abort(404)