Home > database >  How to download response as a pdf where response come from flask api
How to download response as a pdf where response come from flask api

Time:12-27

I want to download my flask API response as a pdf in JavaScript where a response should look like these:

%PDF-1.4%    1 0 obj<</Type /Pages/Count 2/Kids [ 3 0 R 4 0 R ]>>endobj2 0 obj<</Producer (PyPDF2)>>endobj3 0 obj<<

I Want to convert that response into a PDF and download it

CodePudding user response:

first, make a request to the flask API, Get the PDF file as a blob, Create a URL for the blob, Create an anchor element, Set the href and download attributes of the anchor element

CodePudding user response:

Call this function to download your PDF.

async function downloadPDF() {
  // Make a GET request to the Flask API
  const response = await fetch('/api/generate-pdf');

  // Get the PDF file as a blob
  const blob = await response.blob();

  // Create a URL for the blob
  const url = URL.createObjectURL(blob);

  // Create an anchor element
  const a = document.createElement('a');

  // Set the href and download attributes of the anchor element
  a.href = url;
  a.download = 'my-pdf.pdf';

  // Simulate a click on the anchor element
  a.click();

  // Revoke the object URL to release the memory
  URL.revokeObjectURL(url);
}
  • Related