GenweiWu / Blog

个人技术能力提升
MIT License
4 stars 0 forks source link

angular2集成pdfjs,来展示pdf文件 #45

Closed GenweiWu closed 6 years ago

GenweiWu commented 6 years ago
GenweiWu commented 6 years ago

官方指导

1. Download https://github.com/mozilla/pdf.js/archive/gh-pages.zip.

2. Extract the ZIP file (a directory called "pdf.js-gh-pages" will be created).

3. Copy the following directories to your website:

参考:https://github.com/mozilla/pdf.js/wiki/Setup-pdf.js-in-a-website

GenweiWu commented 6 years ago

普通项目中的使用

<a href="/web/viewer.html?file=xxx.pdf">Open yourpdf.pdf with PDF.js</a>

其中的xxx.pdf可以是一个rest请求,只要得到的最终文件是pdf即可

GenweiWu commented 6 years ago

angular2中使用pdfjs

html文件

<iframe [src]="pdfResource" frameborder="0"></iframe>

ts文件


import { Component, OnInit, Input } from '@angular/core';
import {DomSanitizer,SafeResourceUrl} from '@angular/platform-browser';

@Component({ selector: 'pdf-preview', templateUrl: './pdf-preview.component.html', styleUrls: ['./pdf-preview.component.css'] }) export class PdfPreviewComponent implements OnInit { @Input() resourcePath:string; private pdfResource:SafeResourceUrl; constructor(private domSanitizer: DomSanitizer) { }

ngOnInit() { console.log(this.resourcePath); this.pdfResource = this.domSanitizer.bypassSecurityTrustResourceUrl("/assets/pdf/web/viewer.html?file=" + this.resourcePath) }

}



> assets目录
存放上面第一部分提到的web和build文件夹
GenweiWu commented 6 years ago

图片加载blob失败问题

nginx中配置的安全策略会影响资源加载

-add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:; font-src * 'self' 'unsafe-inline' data: https:; img-src * 'self' 'unsafe-inline' data: https:; style-src 'self' 'unsafe-inline'; frame-src 'self'";
+add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:; font-src * 'self' 'unsafe-inline' data: https:; img-src * 'self' blob: 'unsafe-inline' data: https:; style-src 'self' 'unsafe-inline'; frame-src 'self'";