使用react-pdf在html展示pdf文件,达到显示所有页并

2021-01-25  本文已影响0人  寒冰助手

完整代码

import React, { Component, useState } from 'react';
import { Document, Page } from "react-pdf";
import myPdf from './test.pdf'
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;


const pdfFile = myPdf


class Pdf extends Component {
    state = {
        numPages: null,
        pageNumber: 1,
    }

    onDocumentLoadSuccess = ({ numPages }) => {
        this.setState({ numPages });
    }

    render() {
        const { pageNumber, numPages } = this.state;
        var clientWidth = window.screen.width;
        var scale=(clientWidth/595).toFixed(2)
        console.log(scale)
        return (
            <div>
                <Document file={pdfFile}  onLoadSuccess={this.onDocumentLoadSuccess} loading="">
                        {
                            new Array(numPages).fill('').map((item, index) => {
                                return <Page key={index+1} pageNumber={index+1}  scale={scale} />
                            })
                        }
                </Document>
             </div>
        );
    }
}
export default Pdf

关键点

1.把pdf文件放在同级目录后引入

import myPdf from './test.pdf'

2.文件头加上:

import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

否在会报如下错误:


image.png
image.png

3.pdf缩放比例适应页面宽度

//获取页面宽度
var clientWidth = window.screen.width;
//计算缩放比例(595为浏览器控制台获取到的原pdf的canvas属性的宽度,该属性导致pdf宽度无法适配页面宽度)
var scale=(clientWidth/595).toFixed(2)

4.将缩放比例给到page的scale属性

scale={scale}
上一篇 下一篇

猜你喜欢

热点阅读