samedi 26 juin 2021

How to convert a flask html snipped into a pdf when a button gets clicked?

In the body of my index.html I have a div like the one that follows which contains some text as well as an span tag in which the user can enter some input (aka fill the blanks).

index.html

   <div>
      <h3>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Animi, et.</h3>
      <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Iste laboriosam inventore sint non nemo voluptatem magni aperiam quidem cumque eligendi. Lorem ipsum dolor, sit amet consectetur adipisicing elit. <span contenteditable="true" class="badge alert-info nombre" data-placeholder="text" data-focused-advice="start typing"></span> Iste laboriosam inventore sint non nemo voluptatem magni aperiam quidem cumque eligendi.</p>
      <br>
      <button type="submit" onclick="myFunction() class="btn btn-primary mx-auto d-block">Generate PDF</button>
    </div>

app.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def main():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True, port=8000)

style.css

span.badge[contenteditable] {
    display: inline-block;
}
span.badge[contenteditable]:empty::before {
    content: attr(data-placeholder);
    display: inline-block;
}
span.badge[contenteditable]:empty:focus::before {
    content: attr(data-focused-advice);
}

Afterward, the user can click on a button and my goal is to download a pdf. I read this is possible with weasyprint so I started writing some basic code for it which I need to trigger when the button is clicked and pass the HTML above instead of the current placeholder

from weasyprint import HTML, CSS
from weasyprint.fonts import FontConfiguration
placeholder = "<h1>The title</h1>"
font_config = FontConfiguration()
html = HTML(string=placeholder)
css = CSS(string='''
    @font-face {
        font-family: Gentium;
        src: url(http://example.com/fonts/Gentium.otf);
    }
    h1 { font-family: Gentium }''', font_config=font_config)
html.write_pdf(
    'example.pdf', stylesheets=[css],
    font_config=font_config)

I struggle to combine both python and javascript in Flask, so that the whole text above (including the input in the span tag) gets downloaded in a pdf. What should I write in myFunction()?




Aucun commentaire:

Enregistrer un commentaire