mikecousins/react-pdf-js

Is there a way to load a PDF from base64 data?

Closed this issue · 6 comments

Loading a PDF from react-pdf worked this way, could anyone help me out with this?

I'm getting a PDFDocument: stream must have data error whenever I try to load my PDF's

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

Any Updates on the mentioned issue?

Any update on this?
I am facing this issue.

Loading a PDF from react-pdf worked this way, could anyone help me out with this?

I'm getting a PDFDocument: stream must have data error whenever I try to load my PDF's

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

Basically, react-pdf-js supports base 64 string. Different from react-pdf, it is not required to separate the data type data:application/pdf;base64 from the date string in this library. Here is an example, and it works to me.

// data.js
const pdf = `data:application/pdf;base64,JVBERi0xLjYNJeLjz9MNCjEyNCAw...`
export const getData = () => JSON.stringify(pdf)

// PdfViewer.jsx
import * as Data from '../data/pdf'
export default class PdfViewer extends React.Component {
...
render() {
        return (
        <div>
            <PDF
                file={JSON.parse(Data.getData())}
                onDocumentComplete={this.onDocumentComplete}
                page={this.state.page}
            />
            {pagination}
        </div>
        )
    }
}

Another solution would be to turn the base64 string into a blob, then attach the blob to window.URL.createObjectURL, which in turn can be passed to the file prop:

const raw = window.atob(base64);
const rawLength = raw.length;
const blobArray = new Uint8Array(new ArrayBuffer(rawLength));

for (let i = 0; i < rawLength; i++) {
    blobArray[i] = raw.charCodeAt(i);
}

const blob = new Blob([blobArray], {type: 'application/pdf'});

Then

window.URL.createObjectURL(blob)

Seems like this one might be working? Let me know if it's not.

this approach is not working in iphone safari