React-pdf: onLoadSuccess not fired with Uint8Array data

Created on 21 Feb 2018  ·  4Comments  ·  Source: wojtekmaj/react-pdf

I'm using react-pdf in a specific environement ( electron ) so I cannot load the file via http/https but from fs.
It seems that the onLoadSuccess is not fired, is it normal ?
I need to get the number of pages prior of rendering the first page.

question

All 4 comments

Definitely not normal! Does the file load perfectly otherwise? Can you share your implementation of React-PDF here?

Yes , the file is perfectly loaded.

Tried on the stable release and the 3 alpha.

Did I missed something ?

export default class PDFPlayer extends PureComponent {

  state = {
    fileLoaded: 0,
    numPages: null,
    pageNumber: 1,
  }

  componentWillMount() {
    const { filePath } = this.props;
    if (fs.existsSync(filePath)) {
      fs.readFile(filePath, (err, file) => {
        if (err) { console.log(err); }
        this.file = new Uint8Array(file);
        this.setState({ fileLoaded: 1 });
      });
    }
  }

  onLoadSuccess = (pdf) => {
    console.log('onDocumentLoad', pdf);
    this.setState({ numPages: pdf.numPages });
  }

  onRenderSuccess = (page) => {
    console.log(page.originalHeight);
  }

  render() {
    const { fileLoaded } = this.state;
    if (!fileLoaded) return null;
    return (
      <div style={{ ...styles.container, height: document.body.offsetHeight }}>
        <Document
          ref={(doc) => { this.document = doc; }}
          file={{ data: this.file }}
          onLoadSuccess={this.onLoadSuccess}
        >
          <Page onRenderSuccess={this.onRenderSuccess} pageNumber={1} />
        </Document>
      </div>
    );
  }
}

That looks perfectly okay! Wonder if you get at least onSourceSuccess callback...!
By the way, I think you don't need to do this much work.

  1. I believe whatever you get form fs.readFile will also be accepted.
  2. file={this.file} should also be okay.

Also a hint, componentWillMount gets deprecated soon, try loading a document on componentDidMount :)

thanks for the hint , I've changed to componentDidMount


    1. Yep it work without the Uint8Array


    1. No, I have an error when I try to load directly the file without passing the object.

I've found an hack , I just need to know the number of pages after I've loaded the first page , so I'm waiting for the renderSuccess of the first page to get the number of pages in the document state. I'm a bit busy on my project so I didn't get the time to debug this. I'm not sure it's because I'm running on electron or because I'm loading a local file. Anyway , I will keep you updated when I get the time to debug this.

Was this page helpful?
0 / 5 - 0 ratings