Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.1K
Views
¿Cómo enviar un archivo pdf para la respuesta ajax usando un matraz?

Estoy tratando de mostrar un archivo pdf en el navegador sin descargarlo para el usuario. Entonces, actualmente tengo una función de matraz que puede generar un archivo pdf usando el módulo FPDF y necesito que se muestre al usuario en una nueva pestaña.

La función matraz actual es

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

Llamo a la función ajax como

 $("#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 answers
Answer question

0

Con el parámetro as_attachment puede especificar si el navegador debe guardar el archivo u ofrecerlo para su visualización. Si el valor se establece en False , se debe mostrar el archivo. (Verdocumentación )

El siguiente ejemplo también le muestra cómo puede entregar el documento pdf sin guardarlo temporalmente.
El uso de AJAX no es necesario en este caso. Un ancla simple con un objetivo debería ser suficiente.

Matraz (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 (plantillas/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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!