参考文档:
工作学习总结--ng2-pdf-viewer的运用
后台返回pdf的base64字段,用pdf.js展示
base64转文件(blob)遇到的一个问题
例子
demo
准备工作创造一个工程,我创建的是tabs
第一步,安装ng2-pdf-viewer
npm install ng2-pdf-viewer --save
第二步,在需要ng2-pdf-viewer的page或者component中引入,我们一page为例,在tab2中找到tab2.module.ts并引入
import {PdfViewerModule} from 'ng2-pdf-viewer';
@NgModule({
imports: [
...
PdfViewerModule,
...
],
declarations: [Tab2Page]
})
第三步,在tab2.page.html中引入pdf-viewer
src的类型可以是服务器上的PDF也可以是base64
Property Type Required
[src] string, object, UInt8Array Required
<ion-header>
<ion-toolbar>
<ion-title>
Tab Two
</ion-title>
</ion-toolbar>
</ion-header><ion-content >
<pdf-viewer [src]="pdfUrl"
[show-all]="true"
[original-size]="false"
[zoom]=1
[render-text]="false"
[autoresize]="true"
style="display: block;"</pdf-viewer>
</ion-content>
第四步,在tab2.page.ts中进行相关操作
import { Component } from '@angular/core';
import { PdfViewerModule } from 'ng2-pdf-viewer';
import { HttpClient } from "@angular/common/http";
import { HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Component({
selector: 'app-tab2',
templateUrl: 'tab2.page.html',
styleUrls: ['tab2.page.scss']
})
export class Tab2Page {
//PDF base64请求地址
public loanPolicyDownLoadUrl: string = ''
//网页PDF
public pdfUrl: any = "https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf";
constructor(public http: HttpClient) { }
ngOnInit() {
this.loanPolicyDownLoad()
}
//请求
loanPolicyDownLoad() {
let param: any = {
body: {
loanNo: '',
},
serviceCode: '',
}
console.log(param)
let rxjsData = this.angularPost(this.loanPolicyDownLoadUrl, param);
rxjsData.subscribe((response: any) => {
console.log(response)
this.pdfUrl = this.convertDataURIToBinary(response.body.fileBase64Content);
}, (error: Object) => {
// this.hanpublicService.presentLoading("出错啦!")
console.log('出错啦!')
})
}
/*
注
dataURI 是PDF转的base64字符串
*/
convertDataURIToBinary(dataURI) {
var BASE64_MARKER = ';base64,';//声明文件流编码格式
//[RFC2045]中有规定:Base64一行不能超过76字符,超过则添加回车换行符。因此需要把base64字段中的换行符,回车符给去掉。
// var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var newUrl = dataURI.substring(dataURI).replace(/[\n\r]/g, '');
var raw = window.atob(newUrl);//这个方法在ie内核下无法正常解析。
var rawLength = raw.length;
//转换成pdf.js能直接解析的Uint8Array类型
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i) & 0xff;
}
return array;
}
public angularPost(url: string, parameter: any) {
let requestUrl = url
const httpOptions: any = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
return new Observable((observable) => {
this.http.post(requestUrl, parameter, httpOptions).subscribe(response => {
observable.next(response);
}, (error) => {
observable.error(error);
})
});
}
}
网友评论