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

问题描述 投票:0回答:1

这是负责获取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对象的结构

enter image description here

reactjs pdf pdf.js pdf-viewer
1个回答
0
投票

我可以建议包装react-pdf。它是pdf.js的包装。该文档具有道具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>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.