Recommended reading

  • How to display PDF elegantly in front page: Principles

The preparatory work

  1. createreactProject:
create-react-app
Copy the code
  1. Add in the projectpdf.jsRely on
npm install pdfjs-dist || yarn add pdfjs-dist
Copy the code

usepdfjs-dist

Two key files

  • pdf.js
  • pdf.worker.js

How to use

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

These two files contain methods to get, parse, and display PDF documents, but parsing and rendering the PDF takes a long time and can block other JS code. To solve this problem, PDF.js relies on Web Workers introduced by HTML5 to improve performance by removing a lot of CPU operations (such as parsing and rendering) from the main thread.

The PDF.js API returns a Promise that allows us to gracefully handle asynchronous operations. But documentation is sparse, so you can only look up the source code and browse Github

++ Digression: I wrote this while looking at the pdFJS-dist project written by someone else

 pdfjs.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.js');
Copy the code

The react project created using create-react-app cannot use required directly. This error is reported if the react project is created using create-react-app

Looking at the source code can pinpoint the cause of the problem: it must accept strings

Position # PDF. Js/SRC/display/worker_options js Lines 27 fe9260 to 34 in 4
/** 
  * A string containing the path and filename of the worker file. 
  * 
  * NOTE: The `workerSrc` option should always be set.in order to prevent any 
  *       issues when using the PDF.js library. 
  * @var {string} 
  */ 
 GlobalWorkerOptions.workerSrc = 
Copy the code

CND can also be used to solve this problem

pdfjs.GlobalWorkerOptions.workerSrc = "https://cdn.bootcss.com/pdf.js/2.2.228/pdf.worker.js";
Copy the code

Apply colours to a drawing

  1. createcanvasTo render PDF easily
const canvasRef = useRef(null)

<canvas
    ref={canvasRef}
    width={window.innerWidth}
    height={window.innerHeight}
/>
Copy the code
  1. Add js code to render PDF
# Read the PDF file
const loadingTask = pdfjs.getDocument(url);

Get the PDF object
const pdf = await loadingTask.promise;

const firstPageNumber = 1;

# Read page information
const page = await pdf.getPage(firstPageNumber);

Set page zooming
const scale = 1;
const viewport = page.getViewport({scale: scale});

# The following is clearer
# const devicePixelRatio = window.devicePixelRatio;
# const viewport = page.getViewport({scale: scale * devicePixelRatio});


// Prepare canvas using PDF page dimensions
const canvas = canvasRef.current;

const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;

// Render PDF page into canvas context
const renderContext = {
    canvasContext: context,
    viewport: viewport
};
const renderTask = page.render(renderContext);
Copy the code

This renders the PDF to the canvas we just wrote, but this code only renders the first page, rendering different pages by changing firstPageNumber.

GetDocument () : Used to get PDf documents asynchronously, sending multiple Ajax requests to download the documents as blocks. It returns a Promise whose success callback passes an object that contains information about the PDF document, and the code in the callback is executed when the PDF document retrieval is complete. GetPage () : Used to get individual pages in a PDF document. GetViewport () : Returns the page size of the PDf document for the presentation scale provided. Render () : render PDF.Copy the code

This can only meet simple page turning requirements, if you add other requirements, zoom in and out, text copy, can not be changed to meet. We’ll write the next section on how to be able to copy text ==.

Source address: https://github.com/LiuSandy/react-pdf-render