Refer to the PDF – dist

NPM install PDF-dist

Package. json version number

~ matches recent minor dependencies. For example, ~ 1.2.3 matches all 1.2.x versions, but not 1.3.0

^ Match the latest large version dependencies, such as ^1.2.3 will match all 1.x.x versions, including 1.3.0, but not 2.0.0

* means to install the latest version dependencies

Uncaught SyntaxError: Unexpected token

The fixed version number may cause compatibility problems with different versions. Use the official recommended version number

import * as pdfjs from 'pdfjs-dist'
import * as PdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry'
Copy the code

Github.com/mozilla/pdf…

Get file objects
// url must be string, Uint8Array or directly import PDF file
const loadingTask = pdfjs.getDocument(url)
loadingTask.promise.then(pdf= >{# PDF number of pages available in PDF})Copy the code

Get each page object

pdf.getPage(num).then(page= >{# num display per page # page is per page data object})Copy the code
Render to page
var scale = 1.5; # zoom sizevar viewport = page.getViewport({ scale: scale, }); Create a Canvas Canvasvar canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;

var renderContext = {
  canvasContext: context,
  viewport: viewport }; Render page. Render (renderContext);Copy the code
Dynamically set scaling
Set the default zoom ratioconst oriViewport = page.getViewport({ scale: 1 });  
const defaultScale = Math.min(maxWidth, contentWidth) / oriViewport.width; 

var desiredWidth = window.devicePixelRatio; Device pixel ratio makes rendered pages sharper and eliminates blurring caused by PDF zooming in and outconst viewport = page.getViewport({ scale: scale * devicePixelRatio });;
Copy the code

Company bosses optimize PDFJS-DIST using CDN

// Verify the number of PDF pages
if (/\.(pdf)$/i.test(newFile.name)) {
    const reader = new FileReader()
    await reader.readAsArrayBuffer(newFile.file)
    reader.onload = async() = > {await loadScript(
        'https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.min.js'
      )
      const pdfjsLib = window['pdfjs-dist/build/pdf']
      pdfjsLib.GlobalWorkerOptions.workerSrc =
        '/ / cdn.jsdelivr.net/npm/[email protected]/build/pdf.worker.js'
      const loadingTask = pdfjsLib.getDocument(
        new Uint8Array(reader.result)
      )
      const pdfInfo = await loadingTask.promise
      if (pdfInfo.numPages && pdfInfo.numPages > 15) {
        this.$refs.upload.update(newFile, {
          error: 'limit'.active: false.response: {
            error: {
              message: 'Page out of limit'.code: 'type'}}})}}Copy the code