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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
| import * as React from 'react'; import * as PDFJS from 'pdfjs-dist' import * as PDFViewer from 'pdfjs-dist/web/pdf_viewer';
export default class PDF extends React.Component<any, any>{ pageRenderRef: React.RefObject<any>; errorWrapper: React.RefObject<any>; pageRenders: [] pdfViewer: any // 不知道pdfjs导出的数据是什么类型,统一使用any eventBus: any pdfLinkService: any l10n: any pdfHistory: any pdfLoadingTask: any pdfDocument: any // loadingBar: any
constructor(props: any) { super(props) this.pageRenders = []; // 存放每页pdf形成的canvas this.pageRenderRef = React.createRef(); // 渲染pdf的容器 this.errorWrapper = React.createRef(); this.pdfViewer = null this.eventBus = null this.pdfLinkService = null this.l10n = null this.pdfHistory = null this.pdfLoadingTask = null this.pdfDocument = null
this.state = { USE_ONLY_CSS_ZOOM: true, TEXT_LAYER_MODE: 0, // DISABLE MAX_IMAGE_SIZE: 1024 * 1024, CMAP_URL: "https://unpkg.com/pdfjs-dist@2.2.228/cmaps/", // 引入pdf.js的字体 CMAP_PACKED: true, // DEFAULT_URL: "./compressed.tracemonkey-pldi-09.pdf", DEFAULT_URL: 'http://localhost:8082/pdfLocal/compressed.tracemonkey-pldi-09.pdf', // 本地预览 需要代理 DEFAULT_SCALE_DELTA: 1.1, MIN_SCALE: 0.25, MAX_SCALE: 10.0, DEFAULT_SCALE_VALUE: "auto", pdfLoadingTask: null, toPageNumber: '1', preDisabled: false, nextDisabled: false, errorWrapperHide: true, errorMoreInfoHide: true, title: '', url: '', errorMessage: '', errorMoreInfo: '' }
}
componentDidMount() { this.init() this.animationStartedPromise().then(res => { this.open({ url: this.state.DEFAULT_URL }) }) }
animationStartedPromise = () => { return new Promise((resolve) => { window.requestAnimationFrame(resolve); }); }
getloadingBar = () => { let bar = new PDFViewer.ProgressBar("#loadingBar", {}); return PDFJS.shadow(this, "loadingBar", bar); }
/** * 渲染pdf */ open = (params: any) => { if (this.pdfLoadingTask) { // We need to destroy already opened document return this.close().then( () => { // ... and repeat the open() call. return this.open(params); } ); }
let url: string = params.url; let self = this; this.setTitleUsingUrl(url); // Loading document. const loadingTask = PDFJS.getDocument({ url: url, maxImageSize: this.state.MAX_IMAGE_SIZE, cMapUrl: this.state.CMAP_URL, cMapPacked: this.state.CMAP_PACKED, });
this.pdfLoadingTask = loadingTask;
// 进度条 loadingTask.onProgress = (progressData: any) => { self.progress(progressData.loaded / progressData.total); };
return loadingTask.promise.then( (pdfDocument: any) => { console.log('pdfDocument', pdfDocument) // Document loaded, specifying document for the viewer. self.pdfDocument = pdfDocument; self.pdfViewer.setDocument(pdfDocument); self.pdfLinkService.setDocument(pdfDocument); self.pdfHistory.initialize({ fingerprint: pdfDocument.fingerprint });
self.getloadingBar().hide(); // self.setTitleUsingMetadata(pdfDocument); }, (exception: any) => { console.log('exception', exception) let message = exception && exception.message; let l10n = self.l10n; let loadingErrorMessage;
if (exception instanceof PDFJS.InvalidPDFException) { // change error message also for other builds loadingErrorMessage = l10n.get( "invalid_file_error", null, "Invalid or corrupted PDF file." ); } else if (exception instanceof PDFJS.MissingPDFException) { // special message for missing PDFs loadingErrorMessage = l10n.get( "missing_file_error", null, "Missing PDF file." ); } else if (exception instanceof PDFJS.UnexpectedResponseException) { loadingErrorMessage = l10n.get( "unexpected_response_error", null, "Unexpected server response." ); } else { loadingErrorMessage = l10n.get( "loading_error", null, "An error occurred while loading the PDF." ); }
loadingErrorMessage.then((msg: any) => { self.error(msg, { message: message }); }); self.getloadingBar().hide(); } ); }
close = () => { this.setState({ errorWrapperHide: true })
if (!this.pdfLoadingTask) { return Promise.resolve(); }
let promise = this.pdfLoadingTask.destroy(); this.pdfLoadingTask = null;
if (this.pdfDocument) { this.pdfDocument = null;
this.pdfViewer.setDocument(null); this.pdfLinkService.setDocument(null, null);
if (this.pdfHistory) { this.pdfHistory.reset(); } }
return promise; }
progress = (level: any) => { let percent = Math.round(level * 100); // Updating the bar if value increases. if (percent > this.getloadingBar().percent || isNaN(percent)) { this.getloadingBar().percent = percent; } }
error = (message: any, moreInfo: any) => { let l10n = this.l10n; let moreInfoText = [ l10n.get( "error_version_info", { version: PDFJS.version || "?", build: PDFJS.build || "?" }, "PDF.js v{{version}} (build: {{build}})" ), ];
if (moreInfo) { moreInfoText.push( l10n.get( "error_message", { message: moreInfo.message }, "Message: {{message}}" ) ); if (moreInfo.stack) { moreInfoText.push( l10n.get("error_stack", { stack: moreInfo.stack }, "Stack: {{stack}}") ); } else { if (moreInfo.filename) { moreInfoText.push( l10n.get( "error_file", { file: moreInfo.filename }, "File: {{file}}" ) ); } if (moreInfo.lineNumber) { moreInfoText.push( l10n.get( "error_line", { line: moreInfo.lineNumber }, "Line: {{line}}" ) ); } } }
this.setState({ errorWrapperHide: false, errorMessage: message })
Promise.all(moreInfoText).then((parts) => { this.setState({ errorMoreInfo: parts.join("\n") }) }); }
errorClose = () => { this.setState({ errorWrapperHide: true, }) }
errorShowMore = () => {
this.setState({ errorMoreInfoHide: false, })
}
errorShowLess = () => { this.setState({ errorMoreInfoHide: true, })
}
/** * 获取pdf名称 * @param url */ setTitleUsingUrl = (url: string) => { this.setState({ url: url }) let title = PDFJS.getFilenameFromUrl(url) || url; try { title = decodeURIComponent(title); } catch (e) { // decodeURIComponent may throw URIError, // fall back to using the unprocessed url in that case } this.setTitle(title); }
/** * 设置title * @param title pdf名字 */ setTitle = (title: string) => { document.title = title; this.setState({ title: title }) // 传给父级 this.props.getTitle(title) }
init = () => { console.log('PDF init') PDFJS.GlobalWorkerOptions.workerSrc = import('pdfjs-dist/build/pdf.worker')
// 跳页初始化 const eventBus = new PDFViewer.EventBus(); this.eventBus = eventBus;
let linkService = new PDFViewer.PDFLinkService({ eventBus: eventBus, }); this.pdfLinkService = linkService;
let pdfViewer = new PDFViewer.PDFViewer({ container: this.pageRenderRef?.current, eventBus: eventBus, linkService: linkService, l10n: this.state.l10n, useOnlyCssZoom: this.state.USE_ONLY_CSS_ZOOM, textLayerMode: this.state.TEXT_LAYER_MODE, }); this.pdfViewer = pdfViewer;
linkService.setViewer(pdfViewer);
this.l10n = PDFViewer.NullL10n;
this.pdfHistory = new PDFViewer.PDFHistory({ eventBus: eventBus, linkService: linkService, })
linkService.setHistory(this.pdfHistory);
eventBus.on("pagesinit", () => { // We can use pdfViewer now, e.g. let's change default scale. pdfViewer.currentScaleValue = this.state.DEFAULT_SCALE_VALUE; });
eventBus.on( "pagechanging", (evt: any) => { let page: number = evt.pageNumber; // 当前页数 let numPages: number = this.pdfDocument.numPages; // 总页数 this.setState({ toPageNumber: page, preDisabled: page <= 1, nextDisabled: page >= numPages }) // 返回给父级 this.props.getPageNumber(page, numPages) }, true );
}
/** * 前一页 */ previous = () => { if (this.state.preDisabled) return; this.pdfViewer.currentPageNumber--; console.log(this.pdfViewer) }
/** * 后一页 */ next = () => { if (this.state.nextDisabled) return; this.pdfViewer.currentPageNumber++; console.log(this.pdfViewer) }
/** * 缩小 */ zoomOut = (ticks: any) => { let newScale = this.pdfViewer.currentScale; do { newScale = (newScale / this.state.DEFAULT_SCALE_DELTA).toFixed(2); newScale = Math.floor(newScale * 10) / 10; newScale = Math.max(this.state.MIN_SCALE, newScale); } while (--ticks && newScale > this.state.MIN_SCALE); this.pdfViewer.currentScaleValue = newScale; }
/** * 放大 */ zoomIn = (ticks: any) => { let newScale = this.pdfViewer.currentScale; do { newScale = (newScale * this.state.DEFAULT_SCALE_DELTA).toFixed(2); newScale = Math.ceil(newScale * 10) / 10; newScale = Math.min(this.state.MAX_SCALE, newScale); } while (--ticks && newScale < this.state.MAX_SCALE); this.pdfViewer.currentScaleValue = newScale; console.log(this.pdfViewer.currentScaleValue) }
/** * 跳转页数 */ toPage = (page: string | number) => { this.setState({ toPageNumber: page }) if (page) { this.pdfViewer.currentPageNumber = Number(page) } }
render() { return ( <React.Fragment>
<div id="viewerContainer" ref={this.pageRenderRef}> <div id="viewer" className="pdfViewer"></div> </div>
<div id="loadingBar"> <div className="progress"></div> <div className="glimmer"></div> </div>
<div id="errorWrapper" ref={this.errorWrapper} hidden={this.state.errorWrapperHide}> <div id="errorMessageLeft"> <span id="errorMessage">{this.state.errorMessage}</span> <button id="errorShowMore" onClick={this.errorShowMore}>More Information</button> <button id="errorShowLess" onClick={this.errorShowLess}>Less Information</button> </div> <div id="errorMessageRight"> <button id="errorClose" onClick={this.errorClose}>Close</button> </div> <div className="clearBoth"></div> <textarea id="errorMoreInfo" disabled hidden={this.state.errorMoreInfoHide} value={this.state.errorMoreInfo}></textarea> </div>
<footer> <button className="toolbarButton pageUp" title="Previous Page" id="previous" onClick={this.previous}></button> <button className="toolbarButton pageDown" title="Next Page" id="next" onClick={this.next}></button> <input type='text' id="pageNumber" className="toolbarField pageNumber" value={this.state.toPageNumber} onChange={e => this.toPage(e?.target?.value)} size={4} min="1" /> <button className="toolbarButton zoomOut" title="Zoom Out" id="zoomOut" onClick={this.zoomOut}></button> <button className="toolbarButton zoomIn" title="Zoom In" id="zoomIn" onClick={this.zoomIn}></button> </footer> </React.Fragment> ) } }
|