PreviewPdf.js
2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* eslint-disable prefer-destructuring */
/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
import React from 'react';
import { InputItem, Icon } from 'antd-mobile-v2';
import { Document, Page, pdfjs } from 'react-pdf';
import 'antd-mobile-v2/dist/antd-mobile.css';
import pdfstyles from './printpdf.less';
import * as commonUtils from '../../../utils/utils';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;
class CommonPrintPdf extends React.Component {
constructor(props) {
super(props);
this.state = {
pageNumber: 1,
numPages: 1,
};
}
onDocumentLoadSuccess = ({ numPages }) => {
this.setState({ numPages });
};
onPageNumberChange = (e) => {
let value = commonUtils.convertStrToNumber(e);
value = value <= 0 ? 1 : value;
value = value >= this.state.numPages ? this.state.numPages : value;
this.setState({ pageNumber: value });
};
lastPage = () => {
if (this.state.pageNumber === 1) {
return;
}
const page = this.state.pageNumber - 1;
this.setState({ pageNumber: page });
}
nextPage = () => {
if (this.state.pageNumber === this.state.numPages) {
return;
}
const page = this.state.pageNumber + 1;
this.setState({ pageNumber: page });
}
render() {
const {
pageNumber, numPages,
} = this.state;
const { urlPrint } = this.props;
console.log('urlPrint:', urlPrint);
const pageWidth = commonUtils.isNotEmptyNumber(document.body.clientWidth) ? 1000 : 360;
/* 计算缩放比例(595为浏览器控制台获取到的原pdf的canvas属性的宽度,该属性导致pdf宽度无法适配页面宽度) */
const scale = (pageWidth / 595).toFixed(2);
return (
<div
className={pdfstyles.view}
>
<div className={pdfstyles.pageContainer}>
<Document
file={urlPrint}
onLoadSuccess={this.onDocumentLoadSuccess}
>
<Page pageNumber={pageNumber} scale={scale} />
</Document>
</div>
<div className={pdfstyles.pageTool}>
<div className={pdfstyles.left}>
<Icon size="md" type="left" onClick={this.lastPage} />
</div>
<InputItem
value={pageNumber}
onChange={e => this.onPageNumberChange(e)}
type="number"
/><div className={pdfstyles.numPages}> / {numPages}</div>
<div className={pdfstyles.right}>
<Icon size="md" type="right" onClick={this.nextPage} />
</div>
</div>
{/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
{/* <span className="pdfClose"> <a onClick={() => window.history.back(-1)} > <Icon type="cross-circle-o" /></a> </span> */}
</div>
);
}
}
export default CommonPrintPdf;