部署在 Netlify 上时,为什么我的 PDF 没有显示在我的 React 应用程序中?

问题描述 投票:0回答:1

我使用react-pdf npm 包制作了一个简单的react 应用程序。当我在本地(在 localhost:3000 上)运行它时,一切工作正常,但是当我尝试部署它时,未显示 PDF,并且屏幕上显示消息“无法加载文件”(这不是由我,但包裹送了它)。

我试图为该应用程序构建一个 pdf 查看器,它允许您上传文件,将其转换为 base64 格式,然后在单击 PDF 的封面页时显示它。

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;

封面组件/最小化 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;

pdf_viewer.jsx 文件中的代码:

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;

可以使用以下 GitHub 链接查看整个代码:https://github.com/komalioruganti/PDF-Viewer

我试图构建的图片如下:

  1. 本地主机: PDF- cover image
    PDF-viewer

  2. 部署的应用程序:https://main--dreamy-mousse-660d51.netlify.app/

但是当我部署它时,pdf 文件没有显示。部署日志如下:

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: > [email protected] 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
reactjs deployment netlify react-pdf
1个回答
0
投票

我的反应应用程序也有同样的问题。在我的情况下,我想使用“pdfjs”库显示我的简历,但出现错误。尚不确定 netlify 在显示 pdf 时是否有问题。

这是我在 netlify 论坛网站上提出的问题(如果有帮助的话): https://answers.netlify.com/t/pdf-displays-on-local-machine-but-not-when-deployed/98452

© www.soinside.com 2019 - 2024. All rights reserved.