0

I made a simple react app using react-pdf npm package. Everything is working fine when I run it locally(on localhost:3000) but when I try to deploy it, the PDF is not being displayed and the message saying "Failed to load file" is shown on the screen(which is not written by me but the package delivers it).

I was trying to build a pdf-viewer for the app which allows you to upload the file, turn it to base64 format and then display it when you click on the cover page of the PDF.

Code in App.js

import React,{useState} from 'react'
import 'react-pdf/dist/esm/Page/TextLayer.css';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import {  BrowserRouter as Router, Route,Routes } from "react-router-dom";
import './App.css';
import MinimizedPDF from "./MinimizedPDF"
import PdfViewer from './pdf_viewer';

function App() {

  const [selectedFileName, setSelectedFile] = useState(null)
  return (
    <div className="App" >
       
    <Router>
    <Routes>
    { <Route path="/" element={<MinimizedPDF selectedFileName={selectedFileName} setSelectedFile={setSelectedFile}/>}></Route>}
      <Route path="/pdf" element={<PdfViewer selectedFileName={selectedFileName} setSelectedFile={setSelectedFile}/>}></Route>
      </Routes>
    </Router>
    <style>
  @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
</style>

    </div>
  );
}

export default App;

Code in Cover Page Component/ Minimized PDF:

import React from 'react';
import { Document, Page } from 'react-pdf/dist/esm/entry.webpack';
import 'react-pdf/dist/esm/Page/TextLayer.css';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import {useNavigate} from "react-router-dom"

const MinimizedPDF = ({selectedFileName,setSelectedFile}) => {

  const navigate = useNavigate();
  
  const handleselectedFile = e => {
    const file = e.target.files[0];
    const reader = new FileReader();

    reader.onload = () => {
      const base64 = reader.result;
      setSelectedFile(base64);
    };

    reader.readAsDataURL(file);
  };

  return (
    <>
     <input
    type="file"
    name="file"
    onChange={handleselectedFile}/>
     
        <div className='minimized-pdf-wrapper' onClick={()=>{navigate("/pdf")}}>
          <Document file={selectedFileName}>
            <div className='page-wrapper'>
              <Page
                key={1}
                pageNumber={1}
                width={200}
                renderTextLayer='svg'
              />
            </div>
          </Document>
        </div>

    </>
  );
}

export default MinimizedPDF;

Code in pdf_viewer.jsx file :

import React, { useState, useEffect, useRef } from 'react';
import { Document, Page } from 'react-pdf/dist/esm/entry.webpack';
import { BsFillBookmarkFill } from 'react-icons/bs';
import { FaShare } from 'react-icons/fa';

function PdfViewer({selectedFileName}) {
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);
  const [scrollDistance, setScrollDistance] = useState(1)
  const [pageWidth, setPageWidth] = useState(600)
  const wrapperRef = useRef(null);

  useEffect(() => {

    const handleScroll = () => {
      const distance = wrapperRef.current.scrollTop;
      setScrollDistance(distance);
      setPageNumber((Math.floor((distance) / (1.4141 * pageWidth))) + 1)
      setScrollDistance(distance)
      window.addEventListener("resize", handleResize)
    };

    const handleResize = () => {
      if (window.innerWidth < 768) {
        setPageWidth(250)
        setPageNumber(Math.floor((scrollDistance + (1.1 * pageWidth)) / pageWidth))
      }
      console.log(pageWidth)
    }

    const wrapperElement = wrapperRef.current;
    wrapperElement.addEventListener('scroll', handleScroll);

    // Clean up the event listener on component unmount
    return () => {
      wrapperElement.removeEventListener('scroll', handleScroll);
    };
    
    
  }, []);
    
   
    
  

  function onDocumentLoadSuccess({ numPages }) {
    setNumPages(numPages);
    setPageNumber(1);
  }

  function handleChange(e) {
    console.log(e);
  }

  return (
    < >
      <center>
        <div className="pdf-wrapper" ref={wrapperRef}>
          <Document file={selectedFileName} onLoadSuccess={onDocumentLoadSuccess} onChange={handleChange}>
            {Array.from(new Array(numPages), (el, index) => (
              <>
                <div key={index}>
                  <div className="pageNumber-display">
                    Page {pageNumber} out of {numPages}
                    <button className="share-pdf">
                      <FaShare className="share-icon" />
                      Share
                    </button>
                    
                    <button className="bookmarkButton">
                      <BsFillBookmarkFill className="bookmark" />
                      Bookmark
                    </button>
                  </div>

                  <Page width={pageWidth}
                    key={`page_${index + 1}`}
                    pageNumber={index + 1}
                    className="page"
                    onChange={() => {
                      setPageNumber(index);
                    }}
                  />
                  <div className='page-inbetween'></div>
                </div>
              </>
            ))}
          </Document>
        </div>
      </center>
    </>
  );
}

export default PdfViewer;

The whole code can be viewed using the following GitHub link: https://github.com/komalioruganti/PDF-Viewer

The picture of what I was trying to build is as follows:

  1. Local host: PDF- cover image
    PDF-viewer

  2. Deployed app: https://main--dreamy-mousse-660d51.netlify.app/

But the pdf just doesn't get displayed when I deploy it. The deploy log is as follows:

3:51:04 PM: Build ready to start
3:51:11 PM: build-image version: 4b067841aaa59ef71931d3505b98c2bc3e63f36f (focal)
3:51:11 PM: buildbot version: cb022b5c389c78cd673ed1d1d88df2933edea03f
3:51:11 PM: Fetching cached dependencies
3:51:11 PM: Starting to download cache of 183.8MB
3:51:13 PM: Finished downloading cache in 1.774s
3:51:13 PM: Starting to extract cache
3:51:15 PM: Finished extracting cache in 2.327s
3:51:15 PM: Finished fetching cache in 4.167s
3:51:15 PM: Starting to prepare the repo for build
3:51:15 PM: Preparing Git Reference refs/heads/main
3:51:17 PM: Starting to install dependencies
3:51:17 PM: Python version set to 3.8
3:51:17 PM: Attempting Ruby version 2.7.2, read from environment
3:51:18 PM: Using Ruby version 2.7.2
3:51:18 PM: Started restoring cached go cache
3:51:18 PM: Finished restoring cached go cache
3:51:19 PM: go version go1.19.9 linux/amd64
3:51:19 PM: Using PHP version 8.0
3:51:20 PM: Started restoring cached Node.js version
3:51:21 PM: Finished restoring cached Node.js version
3:51:22 PM: v16.20.0 is already installed.
3:51:22 PM: Now using node v16.20.0 (npm v8.19.4)
3:51:22 PM: Enabling Node.js Corepack
3:51:22 PM: Started restoring cached build plugins
3:51:22 PM: Finished restoring cached build plugins
3:51:22 PM: Started restoring cached corepack dependencies
3:51:22 PM: Finished restoring cached corepack dependencies
3:51:22 PM: No npm workspaces detected
3:51:22 PM: Started restoring cached node modules
3:51:22 PM: Finished restoring cached node modules
3:51:23 PM: Installing npm packages using npm version 8.19.4
3:51:25 PM: up to date, audited 1540 packages in 2s
3:51:25 PM: 240 packages are looking for funding
3:51:25 PM:   run `npm fund` for details
3:51:25 PM: 6 high severity vulnerabilities
3:51:25 PM: To address all issues (including breaking changes), run:
3:51:25 PM:   npm audit fix --force
3:51:25 PM: Run `npm audit` for details.
3:51:25 PM: npm packages installed
3:51:25 PM: Install dependencies script success
3:51:25 PM: Starting build script
3:51:26 PM: Detected 1 framework(s)
3:51:26 PM: "create-react-app" at version "5.0.1"
3:51:26 PM: Section completed: initializing
3:51:27 PM: ​
3:51:27 PM: Netlify Build                                                 
3:51:27 PM: ────────────────────────────────────────────────────────────────
3:51:27 PM: ​
3:51:27 PM: ❯ Version
3:51:27 PM:   @netlify/build 29.11.5
3:51:27 PM: ​
3:51:27 PM: ❯ Flags
3:51:27 PM:   baseRelDir: true
3:51:27 PM:   buildId: 646de510ccc94e0008c241cb
3:51:27 PM:   deployId: 646de510ccc94e0008c241cd
3:51:27 PM: ​
3:51:27 PM: ❯ Current directory
3:51:27 PM:   /opt/build/repo
3:51:27 PM: ​
3:51:27 PM: ❯ Config file
3:51:27 PM:   /opt/build/repo/netlify.toml
3:51:27 PM: ​
3:51:27 PM: ❯ Context
3:51:27 PM:   production
3:51:27 PM: ​
3:51:27 PM: Build command from Netlify app                                
3:51:27 PM: ────────────────────────────────────────────────────────────────
3:51:27 PM: ​
3:51:27 PM: $ npm run build
3:51:28 PM: > pdf_viewer@0.1.0 build
3:51:28 PM: > CI=false && react-scripts build
3:51:29 PM: Creating an optimized production build...
3:51:39 PM: Compiled with warnings.
3:51:39 PM: 
3:51:39 PM: [eslint]
3:51:39 PM: src/pdf_viewer.jsx
3:51:39 PM:   Line 40:6:  React Hook useEffect has missing dependencies: 'pageWidth' and 'scrollDistance'. Either include them or remove the dependency array. You can also replace multiple useState variables with useReducer if 'setPageNumber' needs the current value of 'pageWidth'  react-hooks/exhaustive-deps
3:51:39 PM: Search for the keywords to learn more about each warning.
3:51:39 PM: To ignore, add // eslint-disable-next-line to the line before.
3:51:39 PM: File sizes after gzip:
3:51:39 PM:   304.88 kB  build/580dd5552d029be953f8f01f4de55ecd.js
3:51:40 PM: Starting post processing
3:51:39 PM:   156.6 kB   build/static/js/main.b3166fd4.js
3:51:39 PM:   2.45 kB    build/static/css/main.c6d5bc95.css
3:51:39 PM:   1.78 kB    build/static/js/787.b5d1dcb4.chunk.js
3:51:40 PM: Skipping HTML post processing
3:51:39 PM: The project was built assuming it is hosted at /.
3:51:39 PM: You can control this with the homepage field in your package.json.
3:51:39 PM: The build folder is ready to be deployed.
3:51:40 PM: Post processing - header rules
3:51:39 PM: You may serve it with a static server:
3:51:39 PM:   npm install -g serve
3:51:39 PM:   serve -s build
3:51:39 PM: Find out more about deployment here:
3:51:40 PM: Post processing - redirect rules
3:51:39 PM:   https://cra.link/deployment
3:51:39 PM: ​
3:51:39 PM: (build.command completed in 11.7s)
3:51:40 PM: Post processing done
3:51:39 PM: ​
3:51:39 PM: Deploy site                                                   
3:51:39 PM: ────────────────────────────────────────────────────────────────
3:51:40 PM: Section completed: postprocessing
3:51:39 PM: ​
3:51:39 PM: Starting to deploy site from 'build'
3:51:39 PM: Calculating files to upload
3:51:39 PM: 4 new files to upload
3:51:39 PM: 0 new functions to upload
3:51:40 PM: Section completed: deploying
3:51:40 PM: Site deploy was successfully initiated
3:51:40 PM: ​
3:51:40 PM: (Deploy site completed in 360ms)
3:51:40 PM: ​
3:51:40 PM: Netlify Build Complete                                        
3:51:41 PM: Site is live ✨
3:51:40 PM: ────────────────────────────────────────────────────────────────
3:51:40 PM: ​
3:51:40 PM: (Netlify Build completed in 12.1s)
3:51:40 PM: Caching artifacts
3:51:40 PM: Started saving node modules
3:51:40 PM: Finished saving node modules
3:51:40 PM: Started saving build plugins
3:51:40 PM: Finished saving build plugins
3:51:40 PM: Started saving corepack cache
3:51:40 PM: Finished saving corepack cache
3:51:40 PM: Started saving pip cache
3:51:40 PM: Finished saving pip cache
3:51:40 PM: Started saving emacs cask dependencies
3:51:40 PM: Finished saving emacs cask dependencies
3:51:40 PM: Started saving maven dependencies
3:51:40 PM: Finished saving maven dependencies
3:51:40 PM: Started saving boot dependencies
3:51:40 PM: Finished saving boot dependencies
3:51:40 PM: Started saving rust rustup cache
3:51:40 PM: Finished saving rust rustup cache
3:51:40 PM: Started saving go dependencies
3:51:40 PM: Finished saving go dependencies
3:51:40 PM: Build script success
3:51:40 PM: Section completed: building
3:51:41 PM: Uploading Cache of size 183.7MB
3:51:43 PM: Section completed: cleanup
3:51:43 PM: Finished processing build request in 31.759s
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
98k374
  • 1
  • 1

0 Answers0