第一步,在項目目錄中安裝pdf.js組件
npm i pdfjs-dist@1.9.607 (高版本會報錯)
npm install ‑‑save‑dev @types/pdfjs‑dist
第二步
安裝ng2-pdf-viewer@3.0.8 (項目angular版本為4.x以下安裝此版本)
第三步,在項目中新建頁面
ionic g page pdf-viewerPage
第四步,在app.module.ts添加代碼,只貼出添加的代碼
import {PdfViewerModule} from 'ng2-pdf-viewer';
@NgModule({
imports: [
PdfViewerModule,
]
})
第四步,實現方式是點擊觸發模態框,讓PDF文件在模態框中渲染。先在需要響應點擊事件的頁面寫代碼
<div class="puma-common-info puma-info-affix" *ngFor="let item of data.attachment">
<div class="puma-common-message puma-common-btn">
<p class="puma-common-title">{{item.attachmentKey}}</p>
<button ion-button round small color="colorCD9F" (click)="shareButtonSheet(item.attachmentVal,item.attachmentKey)">查看</button>
</div>
</div>
//ts文件
import { ModalController } from 'ionic-angular';
@Component({
selector: 'xxxx-home',
templateUrl: 'xxxx.html'
})
export class XxxxPage {
URL= "https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf";
constructor(public modaCtrl: ModalController ) {
}
/*
* 分享PDF文件
* */
shareButtonSheet(url,fileName)
{
let modal = this.modaCtrl.create("xxxPage",{url:url,fileName:fileName});
modal.present();
}
}
//module.ts
import {PdfViewerModule} from 'ng2-pdf-viewer';
@NgModule({
imports: [
IonicPageModule.forChild(xxxPage),PdfViewerModule
],
})
第五步,寫響應模態框請求的頁面pdf-viewer.html
<ion-content padding >
<pdf-viewer [src]="displayData.pdfSource"
[show-all]="true"
[original-size]="false"
[zoom]=1
[render-text]="false"
[autoresize]="true"
style="display: block" >
</pdf-viewer>
</ion-content>
第六步,pdf-viewer.ts
public pdf: boolean = false;
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.initData();
}
/*
* 初始化數據
* */
initData() {
this.title = this.navParams.get("fileName");
this.url = this.navParams.get("url");
}
參考鏈接
https://www.jianshu.com/p/0012e9b37785
https://www.saninnsalas.com/using-pdf-js-with-ionic-3-x/
https://github.com/VadimDez/ng2-pdf-viewer/issues/210
