17

I am trying to reference PDF.js (by Mozilla) into my React project. However, it is throwing 'Unexpected identifier' error.

I have placed the PDF.js in the public folder and referenced it in my index.html.

File structure:

public
  - index.html
  - pdftojs
    - parsejs.js // < parseFile method in this file will be called
    - pdf-parse.js
    - misc..
src
  - pdftotext
    - parsepdf.js // < page to parse PDF

pdf-parse.js

var PDFJS = null
function render_page(pageData) { ... } // Untouched
async function PDF(...) { ... } // Untouched

exports.pdf = PDF; // Changed this line

parsejs.js from the original library:

8    import pdf from 'pdf-parse.js';
9    const pdfjsLib = require('pdfjs-dist'); // 'require' is undefined too so I don't know what is the correct way
10    
11   function parseFile(file) {

... 
45   }

This file throws Unexpected identifier on Line 8

Parse PDF Page (parsepdf.js)

  process(file) {
     parseFile(file); // calling method in parsejs.js
     ...
  }

which gives 'parseFile' is not defined

2
  • Have you checked github.com/mozilla/pdf.js/wiki/Setup-pdf.js-in-a-website ? Are you using some bundler like webpack ? Commented Mar 27, 2019 at 7:08
  • I have the same issue, although I'm using ES6 syntax. But the most basic thing doesn't work: ``` import pdfJs from 'pdfjs-dist/build/pdf'; ``` Instead, pdfJs comes back undefined. This shouldn't take anything extra to set up. The extra set up has to do with worker-related errors, which could only happen if the lib was loaded in the first place. Commented Nov 9, 2020 at 21:16

5 Answers 5

25

I spent too much time today, piecing together fragments of other answers to this question. So here is a complete answer.

First you install pdfjs-dist:

npm install pdfjs-dist

And here is how to use it in an actual viewer component:

import React, { useEffect, useState, useRef, useCallback } from 'react';
import pdfjsLib from "pdfjs-dist/build/pdf";
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";

export default function PdfViewer({url}){
  const canvasRef = useRef();
  pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;

  const [pdfRef, setPdfRef] = useState();
  const [currentPage, setCurrentPage] = useState(1);

  const renderPage = useCallback((pageNum, pdf=pdfRef) => {
    pdf && pdf.getPage(pageNum).then(function(page) {
      const viewport = page.getViewport({scale: 1.5});
      const canvas = canvasRef.current;
      canvas.height = viewport.height;
      canvas.width = viewport.width;
      const renderContext = {
        canvasContext: canvas.getContext('2d'),
        viewport: viewport
      };
      page.render(renderContext);
    });   
  }, [pdfRef]);

  useEffect(() => {
    renderPage(currentPage, pdfRef);
  }, [pdfRef, currentPage, renderPage]);

  useEffect(() => {
    const loadingTask = pdfjsLib.getDocument(url);
    loadingTask.promise.then(loadedPdf => {
      setPdfRef(loadedPdf);
    }, function (reason) {
      console.error(reason);
    });
  }, [url]);

  const nextPage = () => pdfRef && currentPage < pdfRef.numPages && setCurrentPage(currentPage + 1);

  const prevPage = () => currentPage > 1 && setCurrentPage(currentPage - 1);

  return <canvas ref={canvasRef}></canvas>;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Is there any solution of rendering as a SVG instead of canvas?
When I do this, pdfjsLib is undefined. I have checked and I do have build/pdf.js in node_modules under pdfjs-dist. Anybody else hit this issue?
@JohnValdetine There's an example here of rendering to SVG - but only includes the text nodes github.com/mozilla/pdf.js/tree/master/examples/text-only
@DaveMunger If you get undefined problems, try changing the import statement to import * as pdfjsLib from 'pdfjs-dist/webpack';
9

This import will clear the undefined issue:

import * as pdfjsLib from "pdfjs-dist/build/pdf";

Comments

1

checkout these examples from installing Pdf.js from webpack.

pdf.js

Then this is how you reference and bring in the information into your own project.

    import pdfjsLib from 'pdfjs-dist/webpack';

2 Comments

I found their examples confusing. They require gulp to use webpack...? Very odd.
I had to do import * as pdfjsLib from 'pdfjs-dist/webpack'. This stuff really needs to be better documented.
1

I couldn't start my app, untill I had installed the npm module of previous version npm i [email protected]

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0
   <PDFDownloadLink
          document={
            <PDFReport
              key={report.id}
              report={report}
              account={account}
              user={user}
              isFullPageImage={toggle}
              includeImages={includeImages}
              I18n={I18n}
            />
          }
          fileName={`${report.name}.pdf`}
        >
          {({ blob, url, loading, error }) => {
            console.log('error', error)
            console.log('loading', loading)
            console.log('blob', blob)
            console.log('url', url)

            return loading ? (
              <SpinnerDiv>
                <Spinner />
              </SpinnerDiv>
            ) : (
              <LinkContainer>
                <PdfIcons src={pdf} />
                <p style={{ fontSize: '2rem', fontWeight: 600 }}>
                  {I18n.t('report_download_pdf_button')}
                </p>
              </LinkContainer>
            )
          }}
        </PDFDownloadLink>

1 Comment

Please use above kind of rendering method . Otherwise it will not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.