forked from johnfactotum/foliate-js
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathpdf.js
More file actions
513 lines (458 loc) · 18.2 KB
/
pdf.js
File metadata and controls
513 lines (458 loc) · 18.2 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
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
const pdfjsPath = path => `/vendor/pdfjs/${path}`
import '@pdfjs/pdf.min.mjs'
const pdfjsLib = globalThis.pdfjsLib
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsPath('pdf.worker.min.mjs')
const fetchText = async url => await (await fetch(url)).text()
let textLayerBuilderCSS = null
let annotationLayerBuilderCSS = null
// Track active render tasks per iframe document to cancel superseded renders
const activeRenderTasks = new WeakMap()
// Generation counter per document to detect stale renders after async gaps
const renderGenerations = new WeakMap()
// Set up panning and selection event handlers once per iframe document
const setupPanningEvents = (doc) => {
if (doc._readestEventsInitialized) return
doc._readestEventsInitialized = true
const container = doc.querySelector('.textLayer')
if (!container) return
let isPanning = false
let startX = 0
let startY = 0
let scrollLeft = 0
let scrollTop = 0
let scrollParent = null
const findScrollableParent = (element) => {
let current = element
while (current) {
if (current !== document.body && current.nodeType === 1) {
const style = window.getComputedStyle(current)
const overflow = style.overflow + style.overflowY + style.overflowX
if (/(auto|scroll)/.test(overflow)) {
if (current.scrollHeight > current.clientHeight ||
current.scrollWidth > current.clientWidth) {
return current
}
}
}
if (current.parentElement) {
current = current.parentElement
} else if (current.parentNode && current.parentNode.host) {
current = current.parentNode.host
} else {
break
}
}
return window
}
container.onpointerdown = (e) => {
const selection = doc.getSelection()
const hasTextSelection = selection && selection.toString().length > 0
const elementUnderCursor = doc.elementFromPoint(e.clientX, e.clientY)
const hasTextUnderneath = elementUnderCursor &&
(elementUnderCursor.tagName === 'SPAN' || elementUnderCursor.tagName === 'P') &&
elementUnderCursor.textContent.trim().length > 0
if (!hasTextUnderneath && !hasTextSelection) {
isPanning = true
startX = e.screenX
startY = e.screenY
const iframe = doc.defaultView?.frameElement
if (iframe) {
scrollParent = findScrollableParent(iframe)
if (scrollParent === window) {
scrollLeft = window.scrollX || window.pageXOffset
scrollTop = window.scrollY || window.pageYOffset
} else {
scrollLeft = scrollParent.scrollLeft
scrollTop = scrollParent.scrollTop
}
container.style.cursor = 'grabbing'
}
} else {
container.classList.add('selecting')
}
}
container.onpointermove = (e) => {
if (isPanning && scrollParent) {
e.preventDefault()
const dx = e.screenX - startX
const dy = e.screenY - startY
if (scrollParent === window) {
window.scrollTo(scrollLeft - dx, scrollTop - dy)
} else {
scrollParent.scrollLeft = scrollLeft - dx
scrollParent.scrollTop = scrollTop - dy
}
}
}
container.onpointerup = () => {
if (isPanning) {
isPanning = false
scrollParent = null
container.style.cursor = 'grab'
} else {
container.classList.remove('selecting')
}
}
container.onpointerleave = () => {
if (isPanning) {
isPanning = false
scrollParent = null
container.style.cursor = 'grab'
}
}
doc.addEventListener('selectionchange', () => {
const selection = doc.getSelection()
if (selection && selection.toString().length > 0) {
container.style.cursor = 'text'
} else if (!isPanning) {
container.style.cursor = 'grab'
}
})
container.style.cursor = 'grab'
}
const render = async (page, doc, zoom, pageColors) => {
if (!doc) return
// Increment generation to invalidate any in-progress render for this doc
const generation = (renderGenerations.get(doc) || 0) + 1
renderGenerations.set(doc, generation)
// Cancel any in-progress render task for this document
const existingTask = activeRenderTasks.get(doc)
if (existingTask) {
existingTask.cancel()
activeRenderTasks.delete(doc)
}
const scale = zoom * devicePixelRatio
doc.documentElement.style.transform = `scale(${1 / devicePixelRatio})`
doc.documentElement.style.transformOrigin = 'top left'
doc.documentElement.style.setProperty('--total-scale-factor', scale)
doc.documentElement.style.setProperty('--user-unit', '1')
doc.documentElement.style.setProperty('--scale-round-x', '1px')
doc.documentElement.style.setProperty('--scale-round-y', '1px')
const viewport = page.getViewport({ scale })
// the canvas must be in the `PDFDocument`'s `ownerDocument`
// (`globalThis.document` by default); that's where the fonts are loaded
const canvas = document.createElement('canvas')
canvas.height = viewport.height
canvas.width = viewport.width
const canvasContext = canvas.getContext('2d')
const renderTask = page.render({ canvasContext, viewport, pageColors })
activeRenderTasks.set(doc, renderTask)
try {
await renderTask.promise
} catch {
// Render was cancelled or failed — release canvas bitmap memory
canvas.width = 0
canvas.height = 0
return
} finally {
if (activeRenderTasks.get(doc) === renderTask) {
activeRenderTasks.delete(doc)
}
}
// Bail out if a newer render has started or iframe was removed
if (renderGenerations.get(doc) !== generation || !doc.defaultView) {
canvas.width = 0
canvas.height = 0
return
}
const canvasElement = doc.querySelector('#canvas')
if (!canvasElement) {
canvas.width = 0
canvas.height = 0
return
}
// Release old canvas bitmap memory before replacing
const oldCanvas = canvasElement.querySelector('canvas')
if (oldCanvas) {
oldCanvas.width = 0
oldCanvas.height = 0
}
canvasElement.replaceChildren(doc.adoptNode(canvas))
// Clear text layer before re-rendering to prevent DOM accumulation
const container = doc.querySelector('.textLayer')
container.replaceChildren()
const textLayer = new pdfjsLib.TextLayer({
textContentSource: await page.streamTextContent(),
container, viewport,
})
await textLayer.render()
// Bail out if superseded after async text layer render
if (renderGenerations.get(doc) !== generation) return
// hide "offscreen" canvases appended to document when rendering text layer
// https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/pdf_viewer.css#L51-L58
for (const hiddenCanvas of document.querySelectorAll('.hiddenCanvasElement'))
Object.assign(hiddenCanvas.style, {
position: 'absolute',
top: '0',
left: '0',
width: '0',
height: '0',
display: 'none',
})
// fix text selection
// https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/text_layer_builder.js#L105-L107
const endOfContent = document.createElement('div')
endOfContent.className = 'endOfContent'
container.append(endOfContent)
// Set up panning/selection event handlers once per document
setupPanningEvents(doc)
// Clear annotation layer before re-rendering to prevent DOM accumulation
const div = doc.querySelector('.annotationLayer')
div.replaceChildren()
const linkService = {
goToDestination: () => {},
getDestinationHash: dest => JSON.stringify(dest),
addLinkAttributes: (link, url) => link.href = url,
}
await new pdfjsLib.AnnotationLayer({ page, viewport, div, linkService }).render({
annotations: await page.getAnnotations(),
})
}
const renderPage = async (page, getImageBlob) => {
const viewport = page.getViewport({ scale: 1 })
if (getImageBlob) {
const canvas = document.createElement('canvas')
canvas.height = viewport.height
canvas.width = viewport.width
const canvasContext = canvas.getContext('2d')
await page.render({ canvasContext, viewport }).promise
return new Promise(resolve => canvas.toBlob(blob => {
// Release canvas bitmap memory after extracting the blob
canvas.width = 0
canvas.height = 0
resolve(blob)
}))
}
// https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/text_layer_builder.css
if (textLayerBuilderCSS == null) {
textLayerBuilderCSS = await fetchText(pdfjsPath('text_layer_builder.css'))
}
// https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/annotation_layer_builder.css
if (annotationLayerBuilderCSS == null) {
annotationLayerBuilderCSS = await fetchText(pdfjsPath('annotation_layer_builder.css'))
}
const data = `
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=${viewport.width}, height=${viewport.height}">
<style>
html, body {
margin: 0;
padding: 0;
}
${textLayerBuilderCSS}
${annotationLayerBuilderCSS}
</style>
<div id="canvas"></div>
<div class="textLayer"></div>
<div class="annotationLayer"></div>
`
const src = URL.createObjectURL(new Blob([data], { type: 'text/html' }))
const onZoom = ({ doc, scale, pageColors }) => render(page, doc, scale, pageColors)
return { src, data, onZoom }
}
const makeTOCItem = async (item, pdf) => {
let pageIndex = undefined
if (item.dest) {
try {
const dest = typeof item.dest === 'string'
? await pdf.getDestination(item.dest)
: item.dest
if (dest?.[0]) {
pageIndex = await pdf.getPageIndex(dest[0])
}
} catch (e) {
console.warn('Failed to get page index for TOC item:', item.title, e)
}
}
return {
label: item.title,
href: item.dest ? JSON.stringify(item.dest) : '',
index: pageIndex,
subitems: item.items?.length
? await Promise.all(item.items.map(i => makeTOCItem(i, pdf)))
: null,
}
}
const MAX_CACHED_PAGES = 8
const CALIBRE_NS = 'http://calibre-ebook.com/xmp-namespace'
const CALIBRE_SI_NS = 'http://calibre-ebook.com/xmp-namespace-series-index'
const RDF_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
// Calibre writes series metadata into the XMP packet as
// <calibre:series rdf:parseType="Resource">
// <rdf:value>Name</rdf:value>
// <calibreSI:series_index>1.00</calibreSI:series_index>
// </calibre:series>
const parseCalibreSeriesFromXMP = raw => {
if (!raw || typeof raw !== 'string') return null
let doc
try {
doc = new DOMParser().parseFromString(raw, 'application/xml')
} catch {
return null
}
if (!doc || doc.getElementsByTagName('parsererror').length) return null
const seriesEls = doc.getElementsByTagNameNS(CALIBRE_NS, 'series')
const seriesEl = seriesEls.item(0)
if (!seriesEl) return null
const valueEl = seriesEl.getElementsByTagNameNS(RDF_NS, 'value').item(0)
const name = valueEl?.textContent?.trim()
if (!name) return null
const indexEl = seriesEl.getElementsByTagNameNS(CALIBRE_SI_NS, 'series_index').item(0)
const position = indexEl?.textContent?.trim()
return position ? { name, position } : { name }
}
export const makePDF = async file => {
const transport = new pdfjsLib.PDFDataRangeTransport(file.size, [])
transport.requestDataRange = (begin, end) => {
file.slice(begin, end).arrayBuffer().then(chunk => {
transport.onDataRange(begin, chunk)
})
}
const pdf = await pdfjsLib.getDocument({
range: transport,
wasmUrl: pdfjsPath(''),
cMapUrl: pdfjsPath('cmaps/'),
standardFontDataUrl: pdfjsPath('standard_fonts/'),
isEvalSupported: false,
}).promise
// Get viewport dimensions from first page for fixed-layout rendering
const firstPage = await pdf.getPage(1)
const firstViewport = firstPage.getViewport({ scale: 1 })
const book = { rendition: {
layout: 'pre-paginated',
viewport: { width: firstViewport.width, height: firstViewport.height },
} }
const { metadata, info } = await pdf.getMetadata() ?? {}
// TODO: for better results, parse `metadata.getRaw()`
book.metadata = {
title: metadata?.get('dc:title') ?? info?.Title,
author: metadata?.get('dc:creator') ?? info?.Author,
contributor: metadata?.get('dc:contributor'),
description: metadata?.get('dc:description') ?? info?.Subject,
language: metadata?.get('dc:language'),
publisher: metadata?.get('dc:publisher'),
subject: metadata?.get('dc:subject'),
identifier: metadata?.get('dc:identifier'),
source: metadata?.get('dc:source'),
rights: metadata?.get('dc:rights'),
}
const calibreSeries = parseCalibreSeriesFromXMP(metadata?.getRaw?.())
if (calibreSeries) book.metadata.belongsTo = { series: calibreSeries }
const outline = await pdf.getOutline()
book.toc = outline ? await Promise.all(outline.map(item => makeTOCItem(item, pdf))) : null
const cache = new Map()
const pageCache = new Map()
const getPage = async (i) => {
const cached = pageCache.get(i)
if (cached) {
// Move to end for LRU ordering
pageCache.delete(i)
pageCache.set(i, cached)
return cached
}
const page = await pdf.getPage(i + 1)
pageCache.set(i, page)
// Evict oldest pages when over limit, freeing internal page data
while (pageCache.size > MAX_CACHED_PAGES) {
const oldestKey = pageCache.keys().next().value
const oldPage = pageCache.get(oldestKey)
pageCache.delete(oldestKey)
oldPage?.cleanup()
}
return page
}
book.sections = Array.from({ length: pdf.numPages }).map((_, i) => ({
id: i,
load: async () => {
const cached = cache.get(i)
if (cached) {
// Move to end for LRU ordering
cache.delete(i)
cache.set(i, cached)
return cached
}
const url = await renderPage(await getPage(i))
cache.set(i, url)
// Evict oldest render results when over limit
while (cache.size > MAX_CACHED_PAGES) {
const oldestKey = cache.keys().next().value
const oldEntry = cache.get(oldestKey)
cache.delete(oldestKey)
if (oldEntry?.src) URL.revokeObjectURL(oldEntry.src)
}
return url
},
createDocument: async () => {
const page = await getPage(i)
const doc = document.implementation.createHTMLDocument('')
const canvas = doc.createElement('div')
canvas.id = 'canvas'
doc.body.appendChild(canvas)
const textLayer = doc.createElement('div')
textLayer.className = 'textLayer'
doc.body.appendChild(textLayer)
const annotationLayer = doc.createElement('div')
annotationLayer.className = 'annotationLayer'
doc.body.appendChild(annotationLayer)
// TextLayer requires canvas 2d context for font metrics;
// fall back to manual span construction when unavailable
const probe = doc.createElement('canvas')
if (probe.getContext?.('2d')) {
const textLayerInstance = new pdfjsLib.TextLayer({
textContentSource: await page.streamTextContent(),
container: textLayer, viewport: page.getViewport({ scale: 1 }),
})
await textLayerInstance.render()
} else {
const content = await page.getTextContent()
for (const item of content.items) {
if (item.str) {
const span = doc.createElement('span')
span.textContent = item.str
textLayer.appendChild(span)
}
}
}
return doc
},
size: 1000,
}))
book.isExternal = uri => /^\w+:/i.test(uri)
book.resolveHref = async href => {
const parsed = JSON.parse(href)
const dest = typeof parsed === 'string'
? await pdf.getDestination(parsed) : parsed
const index = await pdf.getPageIndex(dest[0])
return { index }
}
book.splitTOCHref = async href => {
if (!href) return [null, null]
const parsed = JSON.parse(href)
const dest = typeof parsed === 'string'
? await pdf.getDestination(parsed) : parsed
try {
const index = await pdf.getPageIndex(dest[0])
return [index, null]
} catch (e) {
console.warn('Error getting page index for href', href, e)
return [null, null]
}
}
book.getTOCFragment = doc => doc.documentElement
book.getCover = async () => renderPage(await pdf.getPage(1), true)
book.destroy = () => {
// Clean up all cached canvases and revoke blob URLs
for (const [, entry] of cache) {
if (entry?.src) URL.revokeObjectURL(entry.src)
}
cache.clear()
for (const [, page] of pageCache) {
page?.cleanup()
}
pageCache.clear()
pdf.destroy()
}
return book
}