-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathpdf-viewer.html
556 lines (504 loc) · 14.9 KB
/
pdf-viewer.html
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
<link rel="import" href="../polymer/polymer-element.html">
<link rel="import" href="../polymer/lib/mixins/gesture-event-listeners.html">
<link rel="import" href="../paper-spinner/paper-spinner.html">
<link rel="import" href="../paper-toast/paper-toast.html">
<link rel="import" href="../paper-button/paper-button.html">
<link rel="import" href="../iron-resizable-behavior/iron-resizable-behavior.html">
<link rel="import" href="./pdfjs.html">
<!--
`pdf-viewer`
a pdf viewer component
![](demo.gif)
@hero demo.gif
-->
<dom-module id="pdf-viewer">
<template>
<style>
:host {
position: relative;
display: flex;
background: var(--dark-theme-background-color, dimgray);
flex-direction: column;
overflow: hidden;
}
.container {
flex: 1;
overflow: hidden;
position: relative;
}
canvas {
display: block;
margin: 0;
}
canvas:first-of-type {
border-right: 1px solid lightgray;
}
paper-spinner {
position: absolute;
width: 100px;
height: 100px;
top: calc( 50% - 50px);
left: calc( 50% - 50px);
}
.viewer {
display: inline-flex;
box-sizing: border-box;
}
[hidden] {
display: none;
}
.yellow-btn {
text-transform: none;
color: #eeff41;
}
</style>
<div class="container" id="container" on-track="_handleTrack">
<div id="viewer" class="viewer">
<canvas id="viewer1" width="0" height="0"></canvas>
<canvas id="viewer2" width="0" height="0"></canvas>
</div>
<paper-spinner id="spinner"></paper-spinner>
</div>
<paper-toast id="errorDlg" duration="0" text="[[errorMessage]]">
<paper-button on-tap="_closeDlg" class="yellow-btn">[[errorBtnLabel]]</paper-button>
</paper-toast>
</template>
<script>
/* global pdfjsDistBuildPdf */
/**
* `pdf-viewer`
*
* The component wrap the [PDFJS](https://github.com/mozilla/pdf.js) library.
*
* @customElement
* @polymer
* @demo demo/index.html
*/
class PdfViewer extends Polymer.mixinBehaviors([Polymer.IronResizableBehavior, Polymer.GestureEventListeners], Polymer.Element) {
static get is() {
return 'pdf-viewer'
}
static get properties() {
return {
/**
* Path to the PDFJS worker script
*
* If for some reasons, pdfjs is installed in another folder than this package's,
* be aware to update this attribute to the full path of the `pdf.worker.min.js` file.
*/
PDFJS_workerSrc: {
type: String,
value: () => {
return this.importPath + '../pdfjs-dist/build/pdf.worker.min.js'
},
},
/**
* url of the pdf file to display
* @type {String}
*/
src: {
type: String,
value: '',
observer: '_srcChanged',
},
/**
* The page number to display
*
* The first page is 1
* @type {Number}
*/
page: {
type: Number,
reflectToAttribute: true,
notify: true,
observer: '_pageChanged',
},
/**
* total number of pages in the document
* @type {Number}
*/
pages: {
type: Number,
readOnly: true,
reflectToAttribute: true,
notify: true,
},
/**
* the initial zoom when opening a document and
* when the mode change
*
* the available values are :
* - __fit__ : whole page,
* - __fit-width__ : full width
*
* @type {String}
*/
initialZoom: {
type: String,
value: 'fit',
},
/**
* The zoom ratio used
* @type {Numder}
*/
zoomRatio: {
type: Number,
value: 1.25,
},
/**
* The view mode of the document
*
* the available values are :
* - __single__ : single page
* - __double__ : double page side by side
*
* @type {String}
*/
mode: {
type: String,
value: 'single',
observer: '_modeChanged',
},
/**
* import error message for translation
*/
errorMessage: {
type: String,
value: 'Error loading the pdf file',
},
errorBtnLabel: {
type: String,
value: 'Close',
},
_views: {
type: Number,
value: 1,
},
/**
* Internal PDF object
*/
_PDF: {
type: Object,
value: () => {
return {}
},
},
_pageRendering: {
type: Boolean,
value: false,
},
_pageNumPending: {
type: Number,
value: null,
},
/**
* indicates if the first rending has been done
*/
_firstRender: {
type: Boolean,
value: false,
},
_pos: {
type: Object,
value: () => ({ x: 0, y: 0 }),
},
_zoom: {
type: Number,
value: 1,
},
_loaded: {
type: Boolean,
value: false,
},
}
}
constructor() {
super()
this.PDFJS = pdfjsDistBuildPdf
this.PDFJS.GlobalWorkerOptions.workerSrc = this.PDFJS_workerSrc
}
connectedCallback() {
super.connectedCallback()
this.addEventListener('iron-resize', this._recenter)
}
/**
* @event pdf-viewer-error Fired when the download of the pdf failed.
* @param {string} src the source string of the pdf.
*/
_showError(src) {
this.$.errorDlg.fitInto = this.$.container
this.$.errorDlg.open()
this.$.spinner.active = false
this.dispatchEvent(new CustomEvent('pdf-viewer-error', { detail: { src: src } }))
}
_clearView(view) {
const context = view.getContext('2d')
context.clearRect(0, 0, view.width, view.height)
}
/**
* @event pdf-viewer-loaded Fired when the download of the pdf succeed.
* @param {string} src the source string of the pdf.
*/
_srcChanged(newValue, oldValue) {
if (this.$.errorDlg.opened) {
this.$.errorDlg.close()
}
if (!newValue || newValue === oldValue) return
this._loaded = false
this._setPages(null)
this.$.viewer2.hidden = true
this.$.viewer1.hidden = true
this._clearView(this.$.viewer1)
this._clearView(this.$.viewer2)
this.$.spinner.active = true
this.firstRender = false
let src = newValue
if (!navigator.onLine) {
this._showError(src)
return
}
this.PDFJS.getDocument(src)
.then(pdf => {
if (src !== this.src) {
// fake cancel
return
}
this._loaded = true
this._setPages(pdf.numPages)
if (this.page > pdf.numPages) this.page = pdf.numPages
if (this.page < 0) this.page = 1
if (!this.page) this.page = 1
this.dispatchEvent(new CustomEvent('pdf-viewer-loaded', {
detail: { src: src },
}))
this._PDF = pdf
switch (this.initialZoom) {
case 'fit-width':
this.fitWidth()
break
default:
this.fit()
}
})
.catch(e => {
this._showError(src)
})
}
_closeDlg() {
this.$.errorDlg.close()
}
_pageChanged(newValue, oldValue) {
if (!newValue && newValue !== 0) return
if (!this._loaded) return
if (newValue > this.pages) this.page = this.pages
if (newValue < 1) this.page = 1
if (this._PDF.pdfInfo) this._drawPage()
}
_modeChanged(newValue, oldValue) {
switch (this.mode) {
case 'double':
this._views = 2
this.$.viewer2.hidden = false
break
default:
this._views = 1
this.$.viewer2.hidden = true
}
if (this._firstRender) {
this._recenter()
switch (this.initialZoom) {
case 'fit-width':
this.fitWidth()
break
default:
this.fit()
}
}
}
/**
* @event pdf-viewer-outrange Fired when trying to render a non existing page.
*/
/**
* move to the next page
*/
next() {
if (this.page < this.pages) {
this.page += this._views
if (this.page > this.pages) this.page = this.pages
} else {
const event = new CustomEvent('pdf-viewer-outrange')
this.dispatchEvent(event)
}
}
/**
* move to the previous page
*/
previous() {
if (this.page > 1) {
this.page -= this._views
if (this.page === 0) this.page = 1
} else {
const event = new CustomEvent('pdf-viewer-outrange')
this.dispatchEvent(event)
}
}
/**
* display the document full width
*/
fitWidth() {
this._PDF.getPage(this.page)
.then(page => {
let viewport = page.getViewport(1)
let rect = this.$.container.getBoundingClientRect()
const zoom = (rect.width - 20) / (this._views * viewport.width)
if (zoom === this._zoom) { return Promise.resolve() }
this._zoom = zoom
this._drawPage()
})
}
/**
* display the whole page
*/
fit() {
const pageNum = this.page || 1
this._PDF.getPage(pageNum)
.then(page => {
let viewport = page.getViewport(1)
let rect = this.$.container.getBoundingClientRect()
const zoom = Math.min((rect.width - 20) / (this._views * viewport.width), (rect.height - 20) / viewport.height)
if (zoom === this._zoom) { return Promise.resolve() }
this._zoom = zoom
this.page = pageNum
this._drawPage()
})
}
/**
* zoom in
*/
zoomin() {
this._zoom = this._zoom * this.zoomRatio
this._drawPage()
}
/**
* zoom out
*/
zoomout() {
this._zoom = this._zoom / this.zoomRatio
this._drawPage()
}
_renderView(view, pg) {
if (!this._loaded) return
return new Promise((resolve, reject) => {
this._PDF.getPage(pg)
.then(page => {
const viewport = page.getViewport(this._zoom)
view.width = viewport.width
view.height = viewport.height
const context = view.getContext('2d')
const renderContext = {
canvasContext: context,
viewport: viewport,
}
resolve(page.render(renderContext))
})
.catch((e) => {
const context = view.getContext('2d')
context.clearRect(0, 0, view.width, view.height)
resolve()
})
})
}
/**
* @event pdf-viewer-render Fired when a page have been rendered.
* @param {string} page the endered page number.
*/
_drawPage(pg) {
if (!this._loaded) return
if (!pg || isNaN(pg)) pg = this.page
if (this._pageRendering) {
this._pageNumPending = pg
return
}
this._pageRendering = true
this.$.spinner.active = true
const promises = []
if (this.mode === 'single') {
this.$.viewer1.hidden = false
promises.push(this._renderView(this.$.viewer1, pg))
} else {
this.$.viewer2.hidden = false
this.$.viewer1.hidden = false
promises.push(this._renderView(this.$.viewer1, pg - pg % 2))
promises.push(this._renderView(this.$.viewer2, pg - pg % 2 + 1))
}
Promise.all(promises)
.then(() => {
this._firstRender = true
this._pageRendering = false
this.$.spinner.active = false
this._recenter()
if (this._pageNumPending !== null) {
// New page rendering is pending
this._drawPage(this._pageNumPending)
this._pageNumPending = null
}
})
.then(() => {
const event = new CustomEvent('pdf-viewer-render', { detail: { page: this.page } })
this.dispatchEvent(event)
})
}
_handleTrack(evt) {
let tmp
let getDiff = (evt) => {
return {
x: this._trackPos.x - evt.detail.x,
y: this._trackPos.y - evt.detail.y,
}
}
switch (evt.detail.state) {
case 'start':
this._trackPos = {
x: evt.detail.x,
y: evt.detail.y,
}
break
case 'track':
tmp = getDiff(evt)
this.$.viewer.style.transform = `translateX(${this._pos.x - tmp.x}px) translateY(${this._pos.y - tmp.y}px)`
break
case 'end':
tmp = getDiff(evt)
this._pos.x = this._pos.x - tmp.x
this._pos.y = this._pos.y - tmp.y
this._recenter()
break
}
}
_recenter() {
const rect = this.$.container.getBoundingClientRect()
const viewerRect = this.$.viewer.getBoundingClientRect()
if (rect.width > viewerRect.width) {
this._pos.x = (rect.width - viewerRect.width) / 2
}
if (rect.height > viewerRect.height) {
this._pos.y = (rect.height - viewerRect.height) / 2
}
if (rect.width < viewerRect.width && rect.width > viewerRect.width + this._pos.x + 50) {
this._pos.x = rect.width - 50 - viewerRect.width
}
if (rect.width < viewerRect.width && this._pos.x > 50) {
this._pos.x = 50
}
if (rect.height < viewerRect.height && rect.height > viewerRect.height + this._pos.y + 50) {
this._pos.y = rect.height - 50 - viewerRect.height
}
if (rect.height < viewerRect.height && this._pos.y > 50) {
this._pos.y = 50
}
this.$.viewer.style.transform = `translateX(${this._pos.x}px) translateY(${this._pos.y}px)`
}
}
window.customElements.define(PdfViewer.is, PdfViewer)
</script>
</dom-module>