import { Component, ElementRef, OnChanges, AfterViewInit, Input, OnInit } from '@angular/core'; import { RdComponent } from '../../base/rdComponent'; import { ScriptLoaderService } from "../../library/script-loader.service"; import { StyleLoaderService } from "../../library/style-loader.service"; declare const jQuery; declare const pdfjsLib; declare const printJS; @Component({ selector: 'rd-pdf-viewer', template: `
{{state.currentPage}}
{{placeholder}}
` }) export class PDFViewer extends RdComponent implements OnInit, OnChanges, AfterViewInit { constructor(private element: ElementRef, private script: ScriptLoaderService, private style: StyleLoaderService) { super(); this.loadScript(); this.loadStyle(); } @Input("rd-file") inputFile: string; // base64 @Input("rd-url") url: string; @Input("rd-export-url") exportURL: string; @Input("rd-zoom") zoomLevel: number = 1; @Input("rd-placeholder") placeholder: string = "PDF Viewer"; id: string = "pdf_canvas" + Math.random(); canvas; state = { file: null, currentPage: 1, zoom: this.zoomLevel } ngOnInit() { if (this.zoomLevel) this.state.zoom = this.zoomLevel; } ngOnChanges() { if (this.inputFile || this.url) this.getDoc(); } ngAfterViewInit() { this.canvas = jQuery(this.element.nativeElement).find("canvas")[0]; } getDoc() { this.loadScript().then(() => { if (this.inputFile) { pdfjsLib.getDocument({ data: atob(this.inputFile) }).promise.then((pdf) => { this.state.file = pdf; this.render(); }); } else if (this.url) { pdfjsLib.getDocument(this.url).promise.then((pdf) => { this.state.file = pdf; this.render(); }); } }) } render() { this.state.file.getPage(this.state.currentPage).then((page) => { let ctx = this.canvas.getContext('2d'); let viewport = page.getViewport({ scale: this.state.zoom }); this.canvas.width = viewport.width; this.canvas.height = viewport.height; page.render({ canvasContext: ctx, viewport: viewport }); }); } gotoPage(page) { this.state.currentPage += page; this.render(); } zoom(zoomIn) { zoomIn ? this.state.zoom += .1 : this.state.zoom -= .1; this.render(); } loadScript(): Promise { return this.script.load(["./assets/js/pdf.min.js", "./assets/js/print.min.js"]).then(() => { pdfjsLib.GlobalWorkerOptions.workerSrc = "./assets/js/pdf.worker.min.js"; }) } loadStyle() { this.style.load(['./assets/css/print.min.css']); } print() { this.loadScript().then(() => { printJS({ printable: this.inputFile, type: 'pdf', base64: true, showModal: true }); }) } }