Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.1K
Visualizações
How to send a pdf file for ajax response using flask?

I am trying to display a pdf file in the browser without downloading it for the user. So currently I have a flask function that can generate a pdf file using FPDF module and I need it to be displayed to the user in a new tab.

The current flask function is

@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)

I call the ajax function as

$("#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.");
      }
    });
});
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

With the parameter as_attachment you can specify whether the browser should save the file or offer it for display. If the value is set to False, the file should be displayed. (See documentation)

The following example also shows you how you can deliver the pdf document without saving it temporarily.
The use of AJAX is not necessary in this case. A simple anchor with a target should do the trick.

Flask (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>
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda