4

Currently I'm trying to load a PDF using base64 data with this React component react-pdf-js.

I am currently recieving a PDFDocument: stream must have data error when trying to load the PDF in the following manner:

   <PDF
      file={`data:application/pdf;base64,${this.state.base64}`}
      onDocumentComplete={this.onDocumentComplete}
      onPageComplete={this.onPageComplete}
      page={this.state.page}
    />

I have had success loading a PDF onto the page using this React component react-pdf, but the library did not have the ability to implement pagination. The code that worked for that componenet was as follows:

    <Document
      file={`data:application/pdf;base64,${this.state.base64}`}
    >
      <Page pageNumber={this.state.pageNumber} />
    </Document>

I was hoping someone would be able to help me figure out how to load a file using base64 using the react-pdf-js, or point me in a direction to implement pagination with react-pdf?

terrabl
  • 743
  • 3
  • 8
  • 23

2 Answers2

4

You can use embed and it's fairly succinct.

return <embed src={`data:application/pdf;base64,${base64ContentString}`}  type="application/pdf" width="100%"></embed>
mirceta
  • 41
  • 2
1

I've been looking on how to do this as well, and found a way thanks to this entry: Creating a Blob from a base64 string in JavaScript the way to set the pdf file is something like this:

const byteCharacters = atob(response);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
const byteArray = new Uint8Array(byteNumbers);
this.state.pdf = new Blob([byteArray], {type: 'application/pdf'});

The document looks like this:

<Document file={this.state.pdf} > ...

Not sure if I am using state correctly here, I was using state hooks in my code.But using the blob should work.

Gert Hermans
  • 769
  • 1
  • 9
  • 30