添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
八块腹肌的冲锋衣  ·  如何从React Native ...·  5 小时前    · 
傻傻的饺子  ·  Whenever I pass ...·  昨天    · 
机灵的枇杷  ·  Erro "Propriedade ...·  昨天    · 
温暖的金鱼  ·  Typescript + React ...·  昨天    · 
耍酷的柳树  ·  Houston Independent ...·  1 年前    · 
稳重的树叶  ·  囚笼之爱番外_头条·  1 年前    · 

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Before you start - checklist

  • I followed instructions in documentation written for my React-PDF version
  • I have checked if this bug is not already reported
  • I have checked if an issue is not listed in Known issues
  • If I have a problem with PDF rendering, I checked if my PDF renders properly in Mozilla Firefox
  • Description

    After updating the react-pdf library from 5.2.0 to 5.3.0 pdf stopped being rendered on Chrome. All I can see is: Failed to load PDF file.

    On the google chrome console I can find:

    Uncaught ReferenceError: require is not defined

    This problem exists only on google chrome because everything works without any problem on Firefox 88.0.

    Environment

  • Browser: Chrome 90
  • React-PDF version: 5.3.0
  • React version: 17.0.2
  • Webpack version: 4.44.2
  • I managed to solve this problem in the following way:

  • Instead of use 'react-pdf/dist/esm/entry.parcel' or 'react-pdf/dist/umd/entry.parcel' just use only the direct 'react-pdf'
  • Since you are going to use this direct reference so you need to copy 'pdfjs-dist/build/pdf.worker.js' to your public folder
  • Then you'll have to import it in this way: pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.js';
  • I used to use the Document from 'react-pdf/dist/esm/entry.parcel' but since I started having the required error I had to switch to that other way

    abdulrehman1937, makma, dmop, FrankenApps, eduardo-valencia, furkanorhan23, chris-f23, Bakeralnabulsi, n-hendriks, nevenhsu, and mustafabin reacted with thumbs up emoji chris-f23, jhunexjun, and mustafabin reacted with heart emoji All reactions

    I managed to solve this problem in the following way:

  • Instead of use 'react-pdf/dist/esm/entry.parcel' or 'react-pdf/dist/umd/entry.parcel' just use only the direct 'react-pdf'
  • Since you are going to use this direct reference so you need to copy 'pdfjs-dist/build/pdf.worker.js' to your public folder
  • Then you'll have to import it in this way: pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.js';
  • I've been following the suggested steps but i still get the error Uncaught ReferenceError: require is not defined in production (in development it works correctly). Before the error I also see in console Warning: Setting up fake worker.

    import { Document, Page, pdfjs } from 'react-pdf';
    /** /pdf.worker.min.js accessible form public at /pdf.worker.min.js */
    pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.js';
    

    Any other suggestion to overcome the current issue?

    Hi @andreareginato, the only way I know that is going to work is by going to your package.json file and setting the version of react-pdf to 5.2.0 ( directly copied from my package.json file "react-pdf": "5.2.0" ). After explicitly setting the version do a npm i or yarn install so that the new changes take effect.

    Side note:
    Make sure to remove the symbol ^ before the version number of the package as this will cause the package manager npm or yarn to always install the latest version of the package which is the 5.3.0 that has this bug.

    Will work ✅:
    "react-pdf": "5.2.0"

    Won't work 🛑:
    "react-pdf": "^5.2.0"

    slugmandrew, dmop, abitgen, lvnilesh, uwemneku, daweimau, PCOffline, Zoomelectrico, ulrichstark, shadowgroundz, and 2 more reacted with thumbs up emoji slugmandrew, andreareginato, dmop, PCOffline, ulrichstark, and p-harsh reacted with rocket emoji All reactions

    Hi @andreareginato, the only way I know that is going to work is by going to your package.json file and setting the version of react-pdf to 5.2.0 ( directly copied from my package.json file "react-pdf": "5.2.0" ). After explicitly setting the version do a npm i or yarn install so that the new changes take effect.

    Side note:
    Make sure to remove the symbol ^ before the version number of the package as this will cause the package manager npm or yarn to always install the latest version of the package which is the 5.3.0 that has this bug.

    Will work ✅:
    "react-pdf": "5.2.0"

    Won't work 🛑:
    "react-pdf": "^5.2.0"

    This solution worked for me

    import { Document, Page, pdfjs } from 'react-pdf/dist/esm/entry.webpack'
    const url = `//cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`
    pdfjs.GlobalWorkerOptions.workerSrc = url

    work for me

    DoctorSlimm, TheOnlyWayUp, iftazinshaikh, kasumil-das, and W8jonas reacted with hooray emoji W8jonas reacted with heart emoji bogdibota, PCOffline, 3200pro, shashankitsoft, Nxtra, dpittman7, ValentinKarrica, pitsy, DoctorSlimm, kasumil-das, and W8jonas reacted with rocket emoji All reactions Require is not defined - pdf is not rendered on chrome require is not defined - pdf is not rendered on Chrome Jul 29, 2021

    I've set up sample repos on my server here:

    https://projects.wojtekmaj.pl/react-pdf/webpack4/
    https://projects.wojtekmaj.pl/react-pdf/webpack5/

    URLs are self-explanatory I think. Looks like both built and dev code works for me with default entry. I'm using the latest React-PDF version here. Anyone can reproduce this issue on the pages above?

    I have the same problem using react-pdf 5.3.2, react 17.0.2 and create-react-app 4.0.3 (i.e. webapack 4). When I import Document and Page from react-pdf/dist/esm/entry.webpack (or react-pdf/dist/umd/entry.webpack) and build the project, it outputs an extra file (plus a license file) into the build directory which causes the error. It does not appear in development because the build files are not used when running from webpack devServer. I had the error not only in Chrome but also Firefox.

    The solution suggested by @jorge-uproar or import from CDN works for me.

    v5.4.0 that has been released 3 days ago seems to have solve the issue for me.

    Today I have also upgraded (clean install of the dependencies) to Node v16 and npm v7, but do think the above release fixed it. In any case, build the app and deployed it on staging and did not had the error anymore.

    Note: I use the esm version

    import {Document, Page} from 'react-pdf/dist/esm/entry.webpack';
    

    Thanks a lot @wojtekmaj and @njleonzhang !!!

    As of for now "react-pdf": "5.3.2" still has the same issue. Is there any progress on this, I don't want to miss out on newer versions of this great library.

    This seems to be indeed fixed in v5.4.0.
    @tomaszzmudzinski can you confirm and close this issue?

    I tried the first option and unfortunately it was not working with this solution:

    pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';

    The CDN option worked out but I have react-apps that run inside a local context without internet access.

    @wojtekmaj I am also getting the same error after upgraded from 5.7.2 to latest 6.2.0. I am running React 18.x.

    Using import { Document, Page } from "react-pdf/dist/esm/entry.webpack5";

    Its working on my localhost but on production it gives error:
    Warning: Setting up fake worker.
    pdf.worker.fca3091210ba0a730cc1.js:2 Uncaught ReferenceError: require is not defined

    With 5.7.2 it was working fine. Any recommended solution or I should revert to old version?

    For now @LiHaoGit 's CDN solution worked for me, also with webpack5 import.

    I am also using react-pdf version "^6.2.0" and running React "^18.1.0". I tried to implement @LiHaoGit 's CDN solution, but it didnt work for me. It is not throwing any error on the console as well. Below is my code. Any help is highly appreciated.

    import React, { useState } from 'react';
    import { Document, Page, pdfjs } from 'react-pdf/dist/esm/entry.webpack5';
    import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
    import 'react-pdf/dist/esm/Page/TextLayer.css';
    import './PdfViewerTemplate.less';
    const url = //cdn.jsdelivr.net/npm/[email protected]/build/pdf.worker.min.js
    pdfjs.GlobalWorkerOptions.workerSrc = url

    const options = {
    cMapUrl: 'cmaps/',
    cMapPacked: true,
    standardFontDataUrl: 'standard_fonts/',

    export const PdfViewerTemplate = ({props}) => {
    const [pdfFileData, setPdfFileData] = useState(_base64ToArrayBuffer(props));
    const [numPages, setNumPages] = useState(null);
    const [pageNumber, setPageNumber] = useState(1);
    const [renderNavButtons, setRenderNavButtons] = useState(false);

    function _base64ToArrayBuffer(base64) {
      var binary_string = window.atob(base64);
      var len = binary_string.length;
      var bytes = new Uint8Array(len);
      for (var i = 0; i < len; i++) {
          bytes[i] = binary_string.charCodeAt(i);
      return bytes.buffer;
    const onSuccess = () => {
      setPageNumber(1);
      setRenderNavButtons(true);
    const changePage = (offset) => {
      setPageNumber(prevPageNumber => prevPageNumber + offset);
    const previousPage = () => { changePage(-1); }
    const nextPage = () => { changePage(+1); }
    return (
      <div className="Pdfview">
        <div className="Pdfview__container">
        <div className="Pdfview__container__document">
        <Document file={{data: pdfFileData}} 
                  onLoadSuccess={({ numPages }) => {
                    setNumPages(numPages);
                    setRenderNavButtons(true);
                    onSuccess;
                  options={options}>
        <Page pageNumber={pageNumber} width={400} height={500} scale={1.0}/>
        {renderNavButtons &&
          <button
            className={pageNumber <= 1 ? 'disabled-form-button' : 'form-button'}
            onClick={previousPage}
            Previous
          </button>
          <button
            className={pageNumber === numPages ? 'disabled-form-button' : 'form-button'}
            onClick={nextPage}
          </button>
        </div>}
        </Document>
              

    I am running react-pdf 6.2.2 and had this error. I got everything working with the following.
    import { Document, Page, pdfjs } from 'react-pdf';
    pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.2.16.105.js'

    I downloaded the pdf.worker.min.js from this link (https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.worker.min.js) and put it in my public directory named as (pdf.worker.min.2.16.105.js) so I am not dependent on a CDN.

    Hope this helps someone else!

    This library is awesome!

    Was trying to fix this issue, then decided I should see if someone else had it.

    Turns out from all of the folks here having the same issue - it's extremely hard to get a pdf document loaded with a single library on the browser using create-react-app.

    Only solution that worked for me is:

    import { Document, Page, pdfjs } from 'react-pdf/dist/esm/entry.webpack';
    const url = `//cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;
    pdfjs.GlobalWorkerOptions.workerSrc = url;
    

    On react 17, react-scripts 4.0.3

    Same issue for me,

    work around work with both https://cdnjs.cloudflare.com/ajax/libs/pdf.js/{pdfjs.version}/pdf.worker.min.js
    or cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js;

    but we expect the library should come with all the dependencies, @wojtekmaj so I guess this issue is still open, no?

    @wojtekmaj I got this issue only with production build, everything was working locally.

    no sure the samples are using the same dependencies as me
    (basically yarn + typescript + CRA5 + react 18 + webpack5)

    details :

     "dependencies": {
         "react": "^18.2.0",
         "react-pdf": "^6.2.2",
     "devDependencies": {
         "@types/node": "^16.11.65",
         "@types/react": "^18.0.26",
         "@types/react-pdf": "^6.2.0",
         "react-scripts": "^5.0.1",
         "typescript": "^4.9.4",
         "webpack": "^5.75.0"
     "packageManager": "[email protected]"
    

    How I can help ? do you need more details ?

    This bug only happens with create-react apps (I suspect it is something with how babel works with create-react-app). I was able to reproduce the bug on the sample create-react-app-5. I have made a fork to fix the sample create-react-app-5 as it is broken currently and does not work: #1358.

    @wojtekmaj You can go to my fork https://github.com/rashadatjou/react-pdf and when you build the create-react-app-5 sample with yarn build and run it locally e.g. serve -s build you will get the bug that is happening above. I do not know what is causing this though :D

    @nocive this might help

    From the README:

    Standard instructions will also work with Create React App. Please note that in Create React App, you can copy pdf.worker.js file from pdfjs-dist/build to public directory in order for it to be copied to your project's output folder at build time.

    Copy over node_modules/pdfjs-dist/build/pdf.worker.js to public/ when building for production.

    I managed to solve this issue for both development and production

    My setup:
    Browser: Chrome 110 and Firefox 110
    React-PDF version: 6.2.0
    React version: 18.2.0
    Webpack version: 5.64.4 (bundled with react-scripts).
    React-scripts: 5.0.1

    import { Document, Page, pdfjs } from 'react-pdf';
    import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
    import 'react-pdf/dist/esm/Page/TextLayer.css';
    pdfjs.GlobalWorkerOptions.workerSrc = './pdf.worker.min.2.16.105.js';

    So what I did was to follow the advice of zwarrell and download the pdf.worker.min.js and rename it. See the comment link below:
    #782 (comment)

    I put it in my public folder and I put it inside the src to be able to load it while developing.

    In order to have my PDF render properly I imported the following 2 styling files:
    import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
    import 'react-pdf/dist/esm/Page/TextLayer.css';

    I am running react-pdf 6.2.2 and had this error. I got everything working with the following. import { Document, Page, pdfjs } from 'react-pdf'; pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.2.16.105.js'

    I downloaded the pdf.worker.min.js from this link (https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.worker.min.js) and put it in my public directory named as (pdf.worker.min.2.16.105.js) so I am not dependent on a CDN.

    Hope this helps someone else!

    This library is awesome!

    Worked for me too. Thanks.

    webpack: 4
    react: 17.0.2,
    Load worker from CDN solve this error. But we have strict CSP policy and load work worker from CDN is not allowed. The import worker configuration posted in the doc does not work.
    Only solution that worked for me is:

    import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry';
    pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;
    

    @wojtekmaj I suggest to add this to the doc.

    cschulte22, shhonarmandi, SignatureBeef, zachkaigler, moonkid196, tarikt-hybird, and teuber789 reacted with thumbs up emoji zidanomar and teuber789 reacted with heart emoji All reactions

    This final approach seemed to get the file into the build for me, but one tweak: didn't work for my typescript app, due to no declarations file. But simply importing the file was sufficient, then left the existing worker config from the examples:

    import "pdfjs-dist/build/pdf.worker.entry";
    pdfjs.GlobalWorkerOptions.workerSrc = new URL(
      'pdfjs-dist/build/pdf.worker.min.js',
      import.meta.url,
    ).toString();
    wojtekmaj, mamume, realmhamdy, drewpager, nvthai, and mcx3499 reacted with thumbs up emoji FaizanMostafa and eleventhaus reacted with heart emoji All reactions

    If anyone is still facing this issue I have followed this approach: #852 (comment)

    By using approach from @codeWriter6 above I resolved the issue in production but faced an annoying issue in the localhost: "Uncaught runtime errors: Worker was terminated". So to fix that as well I followed the link above.

    My setup:

    "react": "^16.8.6",
    "react-pdf": "^7.4.0"

    The fix from @dmr07 from the link above that worked for me:

    import { pdfjs } from 'react-pdf';
    pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`; 
    

    My setup: reacct-pdf: 6.2.2, webpack: 4 react: 17.0.2, Load worker from CDN solve this error. But we have strict CSP policy and load work worker from CDN is not allowed. The import worker configuration posted in the doc does not work. Only solution that worked for me is:

    import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry';
    pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;
    

    @wojtekmaj I suggest to add this to the doc.

    @wojtekmaj I don't think this issue needs to be reopened, but it is probably worth adding this to the readme like @codeWriter6 suggested. Having struggled with this issue for a couple of days, this is the only solution that ended up working. Interestingly, the solution in the readme did not work, even when copying the worker into the public folder like is done in the create-react-app-5 sample.

    T got the same problem with build not working and normally in local. I have tried copy pdf.worker.min.js to public folder and also tried
    import "pdfjs-dist/build/pdf.worker.entry";
    pdfjs.GlobalWorkerOptions.workerSrc = new URL(
    'pdfjs-dist/build/pdf.worker.min.js',
    import.meta.url,
    ).toString();

    but it not working
    My version is 8.0.2
    Can any one help me plz.