0

I want to enable users to download their latest invoice as PDF when they click on a button.

My Rails API is sending PDF file data like so:

def invoice
  pdf_html = ActionController::Base.new.render_to_string(template: 'invoices/show')
  pdf = WickedPdf.new.pdf_from_string(pdf_html)
  send_data pdf, filename: 'file.pdf'
end

My React frontend requests it like so:

axios.request({
    url: "http://localhost:3001/invoice",
    responseType: 'blob'
  }).then(response => {
    console.log("invoice response:", response);
  }).then(blob => {
    const data = URL.createObjectURL(blob);
    this.setState({ invoicePDFlink: data });
  }).catch(error => {
    console.log("invoice error:", error);
  });

This implementation is based on an answer I found here: Using JS to consume a Rails send_data response

If I run it, the API call throws the following error: TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.

I have since learned that createObjectURL is deprecated. I have found answers for workarounds using Mediastream but I haven't found any alternative for Blobs.

How can I solve this?

EDIT

I solved it myself. Solution below.

Dawesign
  • 643
  • 1
  • 7
  • 25

1 Answers1

0

I found out that it actually works as intended by changing the axios request to the following:

  axios.request({
    url: "http://localhost:3001/invoice",
    responseType: 'blob'
  }).then(response => {
    console.log("invoice response:", response);
    const data = URL.createObjectURL(response.data);
    this.setState({ invoicePDFlink: data });
  }).catch(error => {
    console.log("invoice error:", error);
  });

And URL.createObjectURL is only deprecated when using it for media streams. Source: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

Dawesign
  • 643
  • 1
  • 7
  • 25