I am new new to react, I am trying to display a pdf file on browser. I am getting an error as failed to load PDF. I am trying to run the sample program given in https://www.npmjs.com/package/react-pdf.
App.js
import React, { Component } from 'react';
import { Document, Page } from 'react-pdf';
class MyApp extends Component {
state = {
numPages: null,
pageNumber: 1,
}
onDocumentLoad = ({ numPages }) => {
this.setState({ numPages });
}
render() {
const { pageNumber, numPages } = this.state;
return (
<div>
<Document
file="./1.pdf"
onLoadSuccess={this.onDocumentLoad}
>
<Page pageNumber={pageNumber} />
</Document>
</div>
);
}
}
export default MyApp;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
Error screenshot
The “Failed to Load PDF Document” error message indicates that the web browser you are using, Google Chrome, is trying to open the electronic transcript within its own native PDF viewer. Because the transcript is a secured PDF, it must be opened with Adobe Acrobat Reader.
It is possible by using the fetch() method provided by Java Script. The PDF file will be placed in the public folder of React JS application folder structure. Approach: To accomplish this task we do not need to create any new component, we will use one single component named “App.
If you see 'Invalid PDF Structure' where you expected the PDF to display, this may be due to server configuration problems. Either the encrypted file isn't being streamed correctly to the browser (maybe due to gzip being applied incorrectly), or the decryption key in the browser is stale.
You load the file using file="./1.pdf"
I believe that might be the problem.
If you have a file structure like:
Then you need to move the 1.pdf
to public
folder like this:
Because when your compiled javascript code is being executed from public/bundle.js
and bundle.js
does not know how to get to src/components/1.pdf
in file system.
There might be also a difference between production/development environment if you are using webpack
and webpack-dev-server
.
Look at react-pdf
example. It has flat file structure. That is the reason why it works.
if you are using create-react-app then you need to import differently like
import { Document, Page } from 'react-pdf/dist/esm/entry.webpack'
because it uses webpack under the hood.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With