第一步,在项目目录中安装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