#!/usr/bin/env/ python from sys import stdout from flask import Flask, Response, render_template, request from pagedjs import make_pdf from graft_a_tree import graft_a_tree from io import StringIO import sys import textwrap BASEURL = '' MIN_GROW_YEARS = 0 MAX_GROW_YEARS = 25 app = Flask(__name__) def wrap (text, width): return'\n'.join([(' \\\n').join(textwrap.wrap(line, width=width - 2)) for line in text.splitlines()]) with open('graft_a_tree.py', 'r') as script: source_code = script.read() @app.route('{}/'.format(BASEURL)) def index(): return render_template('index.html', BASEURL=BASEURL) @app.route('{}/graft'.format(BASEURL), methods=['POST']) def graft(): years = max(MIN_GROW_YEARS, min(MAX_GROW_YEARS, int(request.form['years']))) with StringIO() as script_stdout: default_stdout = sys.stdout sys.stdout = script_stdout graft_a_tree(years) content = script_stdout.getvalue() sys.stdout = default_stdout html = render_template('book.html', content=content, source_code=wrap(source_code, 100).replace(' ', ' ').replace('\n', '
')) # print(html) print('html rendered') pdf = make_pdf(html) print('made pdf') r = Response(pdf, mimetype='application/pdf') r.headers.extend({ 'Content-Disposition': 'attachment; filename="grafted-tree.pdf"' }) return r