
from flask import Flask, render_template, request, send_file
from docxtpl import DocxTemplate
import subprocess
import platform

app = Flask(__name__)


@app.route('/')
def index():
    """显示表单页面"""
    return "it works"


@app.route('/generate', methods=['POST'])
def generate():
    """生成 Word 文档"""
    # 1. 获取用户提交的表单数据
    context = request.json;

    if context["tpl"]==None :
        return "请选择模板"

    # 2. 使用 DocxTemplate 渲染模板
    doc = DocxTemplate(context["tpl"])
    doc.render(context)
    savepath = "./save.docx"

    doc.save(savepath)

    if context["type"]=="pdf":
       pdf_output = "save.pdf"
       if platform.system() == "Darwin":
           subprocess.run(["soffice", "--headless",  "--convert-to", "pdf","--outdir","./", savepath])
       else:
           subprocess.run(["libreoffice", "--headless",  "--convert-to", "pdf","--outdir","./", savepath])
       savepath = pdf_output

    # 3. 将生成的文件返回给用户下载
    return send_file(
        savepath,
        as_attachment=True,
        download_name="generated_report.docx"
    )


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=9997)

