我正在尝试使用Angular.io创建pdf-viewer组件,但我不断收到警告:设置虚假工作程序。在Angular.io中设置工作线程的正确方法是什么?这两个库似乎都已加载,但是pdfjs lib无法启动工作线程。使用最新的角度cli创建项目和组件。最新的pdfjs-dist库。
Angular.json
"assets": [
"src/favicon.ico",
"src/assets",
"src/assets/helloworld.pdf"
],
"styles": [
"src/styles.css"
],
"scripts": [
"node_modules/pdfjs-dist/build/pdf.js",
"node_modules/pdfjs-dist/build/pdf.worker.js"
]
pdf-viewer-component.ts
@Component({
selector: 'app-pdf-viewer',
templateUrl: './pdf-viewer.component.html',
styleUrls: ['./pdf-viewer.component.css']
})
export class PdfViewerComponent implements OnInit {
url = '/assets/helloworld.pdf';
pdfjsLib = window['pdfjs-dist/build/pdf'];
constructor() { }
ngOnInit() {
this.loadPdf();
}
loadPdf() {
this.pdfjsLib.GlobalWorkerOptions.workerSrc = 'node_modules/pdfjs-dist/build/pdf.worker.js';
// Asynchronous download of PDF
const loadingTask = this.pdfjsLib.getDocument(this.url);
loadingTask.promise.then(function (pdf) {
console.log('PDF loaded');
// Fetch the first page
const pageNumber = 1;
pdf.getPage(pageNumber).then(function (page) {
console.log('Page loaded');
const scale = 1.5;
const viewport = page.getViewport(scale);
// Prepare canvas using PDF page dimensions
const canvas: HTMLCanvasElement = <HTMLCanvasElement>document.getElementById('the-canvas');
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.then(function () {
console.log('Page rendered');
});
});
}, function (reason) {
// PDF loading error
console.error(reason);
});
}
}