ionic3專案實現線上預覽PDF檔案
阿新 • • 發佈:2018-12-05
這裡參考了大牛提供的預覽外掛完成自己需要實現的功能,ng2-pdf-viewer,該外掛不支援ionic3的懶載入,廢話少說,直接擼程式碼。
第一步,安裝 ng2-pdf-viewer
npm install ng2-pdf-viewer --save
第二步,在專案中新建頁面
ionic g page showpdf
ionic3-cli 生成的page中含有.module.ts檔案,該檔案用於懶載入,刪除該檔案後目錄結構如圖
第三步,在app.module.ts
新增程式碼,只貼出需要新增的程式碼
import {PdfViewerModule} from 'ng2-pdf-viewer'; import { ShowpdfPage } from "../pages/showpdf/showpdf"; @NgModule({ declarations: [ ShowpdfPage ], imports: [ PdfViewerModule, ], entryComponents: [ ShowpdfPage ], })
第四步,預覽實現方式是通過點選來觸發模態框,讓PDF檔案在模態框中進行渲染。先在需要響應點選事件的頁面寫相關程式碼。
//html檔案 <ion-row> <ion-col> <a style="text-decoration:underline"(click)="checkUrl(item.url)">附件</a> </ion-col> </ion-row> //ts檔案 import {ShowpdfPage} from "../showpdf/showpdf"; @Component({ selector: 'page-xxxx', templateUrl: 'xxxx.html' }) export class XxxxPage { constructor(public modalCtrl: ModalController) {} checkUrl(url) { console.log(url) url= 'https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf' //測試資料 let modal: Modal = this.modalCtrl.create(ShowpdfPage, { displayData: { pdfSource: { url: url } } }); modal.present(); } }
第五步,響應模態框請求的頁面ShowpdfPage的介面和ts檔案主要程式碼。
//Showpdf.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> //Showpdf.ts檔案 import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; @Component({ selector: 'page-showpdf', templateUrl: 'showpdf.html', }) export class ShowpdfPage { displayData: any = {}; constructor(public navParams: NavParams) { this.displayData = this.navParams.get('displayData'); } goBack(){ this.navCtrl.pop(); } }
以上是實現PDF檔案瀏覽的所有程式碼,顯示結果很是不錯,也能遠端訪問PDF檔案。