import { DeesElement, property, html, customElement, domtools, TemplateResult } from '@designestate/dees-element'; import { Deferred } from '@pushrocks/smartpromise'; import type pdfjsTypes from 'pdfjs-dist'; declare global { interface HTMLElementTagNameMap { 'dees-pdf': DeesPdf; } } @customElement('dees-pdf') export class DeesPdf extends DeesElement { // DEMO public static demo = () => html` `; // INSTANCE @property() public pdfUrl: string = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/examples/learning/helloworld.pdf'; constructor() { super(); // you have access to all kinds of things through this. // this.setAttribute('gotIt','true'); } public render(): TemplateResult { return html` `; } public static pdfJsReady: Promise; public static pdfjsLib: typeof pdfjsTypes; public async connectedCallback() { super.connectedCallback(); if (!DeesPdf.pdfJsReady) { const pdfJsReadyDeferred = domtools.plugins.smartpromise.defer(); DeesPdf.pdfJsReady = pdfJsReadyDeferred.promise; const loadDeferred = domtools.plugins.smartpromise.defer(); const script = document.createElement('script'); script.addEventListener('load', () => { console.log('pdf.js loaded!'); loadDeferred.resolve(); }); script.src = 'https:////mozilla.github.io/pdf.js/build/pdf.js'; document.getElementsByTagName('head')[0].appendChild(script); // The workerSrc property shall be specified. await loadDeferred.promise; DeesPdf.pdfjsLib = window['pdfjs-dist/build/pdf']; DeesPdf.pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js'; pdfJsReadyDeferred.resolve(); } await DeesPdf.pdfJsReady; this.displayContent(); } public async displayContent() { await DeesPdf.pdfJsReady; // Asynchronous download of PDF const loadingTask = DeesPdf.pdfjsLib.getDocument(this.pdfUrl); loadingTask.promise.then( (pdf) => { console.log('PDF loaded'); // Fetch the first page const pageNumber = 1; pdf.getPage(pageNumber).then((page) => { console.log('Page loaded'); const scale = 10; const viewport = page.getViewport({ scale: scale }); // Prepare canvas using PDF page dimensions const canvas: any = this.shadowRoot.querySelector('#pdfcanvas'); const context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; // Render PDF page into canvas context const renderContext = { canvasContext: context, viewport: viewport, }; const renderTask = page.render(renderContext); renderTask.promise.then(function () { console.log('Page rendered'); }); }); }, (reason) => { // PDF loading error console.error(reason); } ); } }