Forums

Problem creating pdf with pdfkit

Hello,

I have written a small web app to generate a pdf letter using information from a form. I tested the code on my laptop with the development flask server and it runs fine. However, when I try and use the app on this server, it hangs just when I get to the code to generate the PDF.

I never get an error, I checked the logs a bunch of times. It just keeps loading forever. I was wondering if someone could take a look and see if I am doing anything wrong.

My code

from flask import Flask, render_template, request, send_file
import os, random, io, pdfkit

app = Flask(__name__)

@app.route("/")
def main():
    return "<a href='/nice/'>Nice Letter</a><br><a href='/firm/'>Firm Letter</a>"

@app.route("/nice/")
def nice_letter():
    context = {
        "page_title": "Nice Letter",
        "page_header": "Nice Letter",
        "post_location": "/pdf/nice/"
    }
    return render_template("letter.html", **context)

@app.route("/firm/")
def firm_letter():
    context = {
        "page_title": "Firm Letter",
        "page_header": "Firm Letter",
        "post_location": "/pdf/firm/"
    }
    return render_template("letter.html", **context)

@app.route("/pdf/<letter>/", methods=["POST"])
def create_pdf(letter):

    letter_type = letter
    context = {
        "letter_date": request.form["letter_date"],
        "recipient_name": request.form["recipient_name"],
        "patient_name": request.form["patient_name"],
        "appointment_date": request.form["appointment_date"]
    }
    if letter_type == "nice":
        template = render_template("nice_letter.html", **context)
    elif letter_type == "firm":
        template = render_template("firm_letter.html", **context)
    filename = ''.join([f"{random.randint(0, 9)}" for _ in range(10)])
    pdfkit.from_string(template, filename)
    return_data = io.BytesIO()
    with open(filename, "rb") as fo:
        return_data.write(fo.read())
    return_data.seek(0)
    os.remove(filename)
    return send_file(return_data, mimetype="application/pdf", download_name="letter.pdf")

@app.route("/img/")
def send_signature():
    return send_file("signature.png")

See our help page on using send_file on PythonAnywhere: https://help.pythonanywhere.com/pages/FlaskSendFileBytesIO/