import { RhLabelService } from './../../../../label.service'; import { RhBaseDto, RhSafeAny } from 'rh-base/model'; import { Component, ElementRef, Input, OnInit, SimpleChanges, ViewChild } from '@angular/core'; import * as PDFJS from 'pdfjs-dist'; import 'pdfjs-dist/build/pdf.worker.entry'; import { MsgHelper } from 'rh-base/core'; // PDF解析需要依赖pdf.worker文件 PDFJS.GlobalWorkerOptions.workerSrc = (window as RhSafeAny).pdfjsWorker; @Component({ selector: 'rh-material-inventory-label-preview', templateUrl: './material-inventory-label-preview.component.html', styleUrls: ['./material-inventory-label-preview.component.less'] }) export class MaterialInventoryLabelPreviewComponent implements OnInit { @ViewChild('pdfViewerContainer') pdfViewerContainer!: ElementRef; @Input() rhPreviewDto!: RhBaseDto; zoom = 1; rotation = 0; zoomStep = 0.1; rotationStep = 90; currentPdfInfo!: { pdf: RhSafeAny; isFirst: boolean }; pdfLoading = false; isLoadCompleted = false; loadedLabelCount = 0; pdfList: RhSafeAny[] = []; currentPdfIndex = 1; scrollTime: RhSafeAny; constructor(private operator: RhLabelService) {} ngOnInit(): void {} ngOnChanges(changes: SimpleChanges): void { const { rhPreviewDto } = changes; if (rhPreviewDto && rhPreviewDto.currentValue) { this.getPdfInfo(); } } ngAfterViewInit(): void { // 监听scroll事件 setTimeout(() => { this.pdfViewerContainer.nativeElement.onscroll = () => { if (this.scrollTime) { clearTimeout(this.scrollTime); } this.scrollTime = setTimeout(() => this.getCurrentPdfIndex(), 100); }; }); } async getPdfInfo() { this.pdfLoading = true; let res = null; try { res = await this.getPreviewPdfUrl(this.rhPreviewDto); const pdf = await PDFJS.getDocument(res['RenderPdfRouter']).promise; this.currentPdfInfo = { pdf, isFirst: this.rhPreviewDto['SkipCount'] === 0 }; // 是否加载完毕 if (res['SkipCount'] === res['TotalCount']) { this.isLoadCompleted = true; } // 更新标签数量 this.loadedLabelCount += pdf.numPages; // 渲染pdf this.handlePdfUrlInfo(); } catch (error: RhSafeAny) { MsgHelper.ShowWarningMessage(`预览失败!${error?.message || JSON.stringify(error)}`); } finally { this.pdfLoading = false; } } async handlePdfUrlInfo() { if (this.currentPdfInfo.isFirst) { // 首次传入 this.pdfList = []; this.currentPdfIndex = 1; const e = this.pdfViewerContainer && this.pdfViewerContainer.nativeElement && this.pdfViewerContainer.nativeElement.querySelector('canvas'); let first = e && e.firstElementChild; while (first) { first.remove(); first = e && e.firstElementChild; } } const pdf = this.currentPdfInfo.pdf; this.pdfList.push(pdf); this.renderPdf(pdf, this.pdfList.length - 1); } async renderPdf(pdf: RhSafeAny, pdfIndex: number) { const pageNum = pdf.numPages; for (let index = 1; index <= pageNum; index++) { let isNewCanvas = false; const canvasId = `Pdf${pdfIndex}_Page${index}`; const page = await pdf.getPage(index); const viewport = page.getViewport({ scale: this.zoom * 2, rotation: this.rotation }); let canvas = document.getElementById(canvasId) as HTMLCanvasElement; if (!canvas) { canvas = document.createElement('canvas'); canvas.id = canvasId; isNewCanvas = true; } const context = canvas.getContext('2d'); canvas.width = viewport.width; canvas.height = viewport.height; // canvas.style.width = `${70 * this.zoom}%`; canvas.style.boxShadow = '1px 1px 5px 5px grey'; canvas.style.margin = '5px 0'; page.render({ canvasContext: context, viewport }); if (isNewCanvas) { this.pdfViewerContainer.nativeElement.insertBefore(canvas, this.pdfViewerContainer.nativeElement.lastChild); } } } updateSize() { this.pdfList.forEach((value, index) => this.renderPdf(value, index)); } getCurrentPdfIndex() { const canvasItemList = this.pdfViewerContainer.nativeElement.getElementsByTagName('canvas') || []; const canvasItem = canvasItemList[0]; if (canvasItem) { const scrollTop = this.pdfViewerContainer.nativeElement.scrollTop; const canvasHeight = canvasItem.offsetHeight + 10; const res = scrollTop / canvasHeight; const index = (Math.ceil(res) - res >= 0.75 ? Math.floor(res) : Math.ceil(res)) + 1; if (index > this.loadedLabelCount) this.currentPdfIndex = this.loadedLabelCount; else this.currentPdfIndex = index; } } handle(type: 'zoomIn' | 'zoomOut' | 'trunRight' | 'trunLeft' | 'reset') { if (type === 'zoomIn') { this.zoom += this.zoomStep; } else if (type === 'zoomOut') { this.zoom -= this.zoomStep; } else if (type === 'trunRight') { this.rotation += this.rotationStep; } else if (type === 'trunLeft') { this.rotation -= this.rotationStep; } else if (type === 'reset') { this.zoom = 1; this.rotation = 0; } else { return; } this.updateSize(); } /** 获取渲染生成的pdf路径 */ getPreviewPdfUrl(dto: RhBaseDto): Promise { return new Promise((resolve, reject) => { this.operator.LabelPreviewByLocal(dto).subscribe( (result) => { if (result.Success) { resolve(result.Attach); } else { reject(result.Message); } }, (error) => { reject(error); } ); }); } loadMore() { this.rhPreviewDto['SkipCount'] = this.loadedLabelCount; this.getPdfInfo(); } }