import Page from './Page.js'; import Highlighter from './Highlighter.js'; const element = ( id ) => document.getElementById( id ); export default class Pdf { constructor( containerId ) { const workerSrc = new URL('./pdf.worker.min.mjs', import.meta.url).href; pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc; this.container = element( containerId ); this.url = this.container.getAttribute( 'data-filename' ); this.pages = []; this.scale = this.calculateScale(); window.addEventListener('resize', this.handleResize.bind(this)); this.load(); } calculateScale() { const maxWidth = window.innerWidth - 40; return maxWidth; } handleResize() { const newScale = this.calculateScale(); if (Math.abs(this.scale - newScale) > 20) { this.scale = newScale; this.container.innerHTML = ''; this.pages = []; this.load(); } } async load() { try { const loadingTask = pdfjsLib.getDocument( this.url ); const pdfDoc = await loadingTask.promise; this.pdfDoc = pdfDoc; this.numPages = pdfDoc.numPages; await this.render(); } catch (error) { console.error('Error loading PDF:', error); } } async render() { const firstPage = await this.pdfDoc.getPage(1); const viewport = firstPage.getViewport({ scale: 1.0 }); const scaleFactor = this.scale / viewport.width; for( let pageNum = 1; pageNum <= this.pdfDoc.numPages; pageNum++ ) { try { const pdfPage = await this.pdfDoc.getPage( pageNum ); const page = new Page( this.container, pdfPage, pageNum, scaleFactor ); await page.render(); this.pages.push( page ); } catch (error) { console.error(`Error rendering page ${pageNum}:`, error); } } this.initializeHighlighter(); } initializeHighlighter() { this.highlighter = new Highlighter( this ); this.highlighter.setupEventListeners(); return this.highlighter; } getHighlighter() { return this.highlighter; } getPageCount() { return this.pdfDoc ? this.pdfDoc.numPages : 0; } getPageElements() { return this.pages.map( page => page.getPageElement() ); } getTextLayers() { return this.pages.map( page => page.getTextLayer() ); } }