如何使用 pdf.js 创建的自定义 pdf 查看器呈现 pdf 的 20%

How to render 20% of a pdf with custom pdf viewer created with pdf.js

这是负责获取pdf的代码。然后它将 pdf 传递给 pdf 查看器以进行呈现。我不想渲染整个 pdf。相反,我只想呈现 pdf 的一部分,例如前 5 页或页面的 20%。下面的代码使用 pdfjs,下面的代码在 PDFJS 仓库中可用。您可以通过 https://github.com/mozilla/pdf.js/blob/master/examples/mobile-viewer/viewer.js

访问整个代码
private open (params) {
    let url = params.url
    let self = this
    this.setTitleUsingUrl(url)
    // Loading document.
    let loadingTask = pdfjsLib.getDocument({
      url: url,
      withCredentials: true,
      maxImageSize: MAX_IMAGE_SIZE,
      cMapPacked: CMAP_PACKED
    })
    this.pdfLoadingTask = loadingTask

    loadingTask.onProgress = function (progressData) {
      self.progress(progressData.loaded / progressData.total)
    }

    return loadingTask.promise.then(function (pdfDocument) {
      // Document loaded, specifying document for the viewer.
      console.log(pdfDocument); // The pdf object. picture content below

      // The document is being passed to the viewer for rendering
      // I want to pass just 15% of the document to the user to view
      self.pdfDocument = pdfDocument;
      self.pdfViewer.setDocument(pdfDocument)
      self.pdfLinkService.setDocument(pdfDocument)
      self.pdfHistory.initialize(pdfDocument.fingerprint)
      self.loadingBar.hide()
      self.setTitleUsingMetadata(pdfDocument)
    }

下图是pdf对象的结构

我可以推荐一个包 react-pdf。它是 pdf.js 的包装。该文档将 props onLoadSuccess 作为以对象作为参数的函数。据我所知,在此对象中您可以找到 numPages - 总页数。您可以像 Math.floor(0.2*numPages) 一样操纵此数字,并仅呈现此页数。但是,阅读文档 MB 您可以找到更好的解决方案。

更新:

import React, { Component } from 'react';
import { Document, Page } from 'react-pdf';

class MyApp extends Component {
  state = {
    numPages: null,
  }

  onDocumentLoadSuccess = ({ numPages }) => {
    this.setState({ numPages: Math.floor(0.2 * numPages) });
  }

  render() {
    const { numPages } = this.state;

    return (
      <div>
        <Document
          file="somefile.pdf"
          onLoadSuccess={this.onDocumentLoadSuccess}
        >
          {Array.from({length: numPages}, (v, i) => i).map(i => (
            <Page key={i} pageIndex={i} />
          ))}
        </Document>
      </div>
    );
  }
}