show pdf in browser from HTTP.get('/my_pdf')

56 Views Asked by At

Ηι!

I use HTTP.get('/ehde_pdf') that through routes.rb calls a controller method that executes this code:

send_data(
          "#{Rails.root}/tmp/ehde_pdf.pdf",
          filename: "your_custom_file_name.pdf",
          type: "application/pdf"
      )

which returns pdf data to the browser, but it's doesn't show up in our page as download prompt. I can see from e.g. Mozilla Developer Tools -> Network that browser gets file data and I can download it with double-click: enter image description here

Is there any way that I can get file data from HTTP.get('/ehde_pdf') and show the download prompt directly?

Thanx!!!

2

There are 2 best solutions below

0
On

Correction: the controller code is

send_file(
      "#{Rails.root}/tmp/ehde_pdf.pdf",
      filename: "your_custom_file_name.pdf",
      type: "application/pdf"
  )
0
On

You want to use a javascript blob in this case. You can do something like this:


(...some api call here)
  .then(res => {
    const blob = new Blob([res.data]);
    const link = document.createElement(triggerTag);
    link.href = window.url.createObjectURL(blob);
    link.download = 'some_file_name';
    link.click();
    window.URL.revokeObjectURL(link.href);
  })
  .catch(....);

This way you can programmatically trigger the download when the user clicks on a button to download the pdf.