1

I am setting up a simple React UI to view pdf files. Currently I have a component defined as PDFViewer which is a block that I would like to display pdf files just like it is done using regular iframe for html/css. There are similar questions but it is using a backend. I just need the pdf file to view on localhost

I tried iframe, img, react-pdf and no luck so far.

    import React, { Component } from 'react';
    import { Page } from 'react-pdf';
    import { Document } from 'react-pdf/dist/entry.webpack';
    import { pdfjs } from 'react-pdf';
    pdfjs.GlobalWorkerOptions.workerSrc`//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
    export default class PDFViewer extends Component {
    state = {
        numPages: null,
        pageNumber: 1,
      }

      onDocumentLoadSuccess = ({ numPages }) => {
        this.setState({ numPages });
      }


  render() {
    const { pageNumber, numPages } = this.state;

    return (
      <div>
        <Document
          file={{
            url: process.env.PUBLIC_URL +"/pdf_file_which_inside_public_dir.pdf"
          }}
          onLoadSuccess={this.onDocumentLoadSuccess}
        >
          <Page pageNumber={pageNumber} />
        </Document>
        <p>Page {pageNumber} of {numPages}</p>
      </div>
    );
  }
}

I expect the pdf file to be rendered just like it is using a regular iframe. It is only one page so i could care less about the page next prev option.

  • Possible duplicate of [Display PDF in reactJS](https://stackoverflow.com/questions/45596329/display-pdf-in-reactjs) – DCTID Jul 26 '19 at 23:57
  • That thread is for pdf file on a deployed server. However I found a solution; It appeared that I just had to either use an Iframe or REACT pdf viewer but with the file being inside the public directory. It also did not like "process.env.PUBLIC_URL" I just have to write "/pdf_file_which_inside_public_dir.pdf" for the url variable. – Yehia Qtaish Jul 30 '19 at 18:41

0 Answers0