0

I am trying to download a server side generated pdf file in client, which i get with axios and save it in redux and using FileSaver to download it.

const getTicketPdf = ({ userID, ticketID }) =>
    requestApi(`/users/${userID}/tickets/${ticketID}/pdf`, {
        method: 'get',
    });

requestApi gets me all neccessary headers so that i can download the file.

the data is then stored in redux like this:

data: "%PDF-1.4\n3 0 obj\n<</Type /Page\n/Parent 1 0 R\n/MediaBox [0 0 595.00 842.00]\n/Resources 2 0 R\n/Contents 4 0 R>>\nendobj\n4 0 obj\n<</Filter /FlateDecode /Length 64>>\nstream\nx�3R��2�35W(�*T0P�R0T(\u0007�Y@�\u000e��@Q…"

i call it in render with:

  <div>
        <button onClick={ () => this.getPdf(ticket) }>PDF</button>
    </div>

getPdf = ticket => {
    const blob = new Blob([ticket]);
    FileSaver.saveAs(blob, 'Ticket.pdf');
}

I am always getting the following error:

TypeError: Cannot read property 'saveAs' of undefined

i tried also to set

responseType: 'blob'

but this doesn't help either.

Next thing I testet was with react-pdf library, where I managed to display pdf in Component, but i cant print it. User should only habe to save it and then print it locally (or at least show it in separate tab as PDF, which i tried with window.open() as base64 encoded string).

How can I download a server side generated PDF otherwise? Are there any better ways?

Unfortunately I have to set HTTP Headers in order to get that file.

Thanks in advance.

Michael Ploeckinger
  • 1,616
  • 1
  • 11
  • 24

2 Answers2

1

The error stems from the fact that there is no FileSaver object (or rather, it's non-standard).

It seems to be polyfilled by this third-party library: https://github.com/eligrey/FileSaver.js

AKX
  • 152,115
  • 15
  • 115
  • 172
  • 1
    Thanks! the reason was i destructered the import like: import { FileSaver } from 'file-saver'; but this works: import FileSaver from 'file-saver'; – Michael Ploeckinger Jul 17 '18 at 12:32
0

The error you are seeing is caused by a reference to an undefined variable FileSaver - I guess that you are using FileSaver.js, and need to fix the import. You should also bear in mind that FileSaver is deprecated in favour of the download attribute. See this answer for details on how to use it.

Either way, in the interests of keeping your store light, you should save a reference to the PDF in your Redux store, rather than the string itself.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141