title: Using JS to consume a Rails send_data response
body: <p>I have a VueJS frontend that is connected to a Rails API backend.</p>
  
  <p>In one of the endpoints, I am using <a href="https://github.com/mileszs/wicked_pdf" rel="nofollow noreferrer">WickedPDF</a> to generate a PDF. When I open the URL itself in a browser, the PDF downloads fine and works exactly as expected. When I send a request via Vue, the API responds with a weird looking string that looks like this:</p>
  
  <pre><code>%PDF-1.4
  1 0 obj
  &lt;&lt;
  /Title (��)
  /Creator (��wkhtmltopdf 0.12.4)
  /Producer (��Qt 4.8.7)
  /CreationDate (D:20190222102025+02'00')
  &gt;&gt;
  endobj
  3 0 obj
  &lt;&lt;
  /Type /ExtGState
  /SA true
  /SM 0.02
  /ca 1.0
  /CA 1.0
  /AIS false
  ...
  </code></pre>
  
  <p>I am not really sure what data type this is? I initially thought that it might be a BLOB, but I have no idea. I followed the logic outlined <a href="https://blog.jayway.com/2017/07/13/open-pdf-downloaded-api-javascript/" rel="nofollow noreferrer">here</a>  to parse the response from my rails api, which did download a PDF to chrome. When opening this PDF, it is blank and the file name at the top of the chrome browser is a combination of weird chars. This makes me think that I am not converting the response in the correct way and some encoding issue ends up happening.</p>
  
  <p>Here is my Rails API code:</p>
  
  <pre><code>def pdf
    pdf_html = ActionController::Base.new.render_to_string(
      template: 'api/v1/exporters/pdf',
      layout: 'pdf',
      page_size: 'A4',
      formats: :html,
      encoding: 'utf8',
      margin: {
        top: 20,
        left: 20,
      }
    )
    pdf = WickedPdf.new.pdf_from_string(pdf_html)
    send_data(
      pdf,                                  
      filename: 'download.pdf',                     
      type: 'application/pdf',                      
      disposition: 'attachment'
    )
  end
  </code></pre>
  
  <p>Here is the JS function from the link above. I am passing the Rails response body (which when console logged is the weird looking char set in the first code block) as the only param:</p>
  
  <pre><code>showFile(blob){
    var newBlob = new Blob([blob], {type: "application/pdf"})
  
    if (window.navigator &amp;&amp; window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(newBlob);
      return;
    } 
  
    const data = window.URL.createObjectURL(newBlob);
    var link = document.createElement('a');
    link.href = data;
    link.download="file.pdf";
    link.click();
    setTimeout(function(){
      window.URL.revokeObjectURL(data);
    , 100}
  }
  </code></pre>
  
  <p>Can anyone help point me in the right direction as to how to configure this in the right way or how to do it in a different/better way? Even a confirmation of what kind of data type the response is might help me.</p>