如何使用 Flask 发送 ajax 响应的 pdf 文件?

How to send a pdf file for ajax response using flask?

我试图在浏览器中显示 pdf 文件而不为用户下载它。所以目前我有一个可以使用 FPDF 模块生成 pdf 文件的 flask 函数,我需要它在新选项卡中显示给用户。

当前flask函数是

@app.route('/pdf/create', methods=['GET', 'POST'])
def create_pdf():
    if not session.get('email'):
        return redirect(url_for('login_page'))
    email = session.get('email')
    pdf = FPDF('P', 'mm', "A4")
    pdf.add_page()
    .... pdf making ...
    pdf.output(f"pdf/mypdf.pdf")
    return send_file(f"pdf/mypdf.pdf",
                     mimetype='application/pdf',
                     attachment_filename=f"My file.pdf",
                     as_attachment=True,
                     cache_timeout=-1)

我将 ajax 函数称为

$("#viewFile").on("click",function(){

    $.ajax({
      url: "{{url_for('create_pdf')}}",
      type: "get",
      data: {text: mytext},
      success: function(response) {
        window.open(response);
      },
      error: function(xhr) {
        alert("Error: Failed to save notes.");
      }
    });
});

使用参数 as_attachment,您可以指定浏览器是保存文件还是显示文件。如果该值设置为 False,则应显示该文件。 (参见 documentation

下面的例子还向您展示了如何在不临时保存的情况下发送pdf文档。
在这种情况下不需要使用 AJAX。一个带有目标的简单锚点就可以解决问题。

烧瓶 (app.py)
from flask import (
    Flask,
    render_template,
    send_file
)
from fpdf import FPDF
import io

app = Flask(__name__)

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

@app.route('/pdf/create')
def create_pdf():
    pdf = FPDF()
    pdf.set_title('My Example PDF')
    pdf.set_author('Artist Unknown')
    pdf.set_subject('Creation of a PDF')
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)
    pdf.cell(40, 10, 'Hello World')

    stream = io.BytesIO(pdf.output(dest='S').encode('latin-1'))
    return send_file(
        stream,
        mimetype='application/pdf',
        attachment_filename='example.pdf',
        as_attachment=False
    )
HTML (templates/index.html)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <a href="{{ url_for('create_pdf') }}" target="_blank">Download</a>
  </body>
</html>