完整代码
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 (
{
new Array(numPages).fill('').map((item, index) => {
return
})
}
);
}
}
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}