This repository has been archived by the owner on Jun 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
pdf-view.android.ts
80 lines (64 loc) · 2.04 KB
/
pdf-view.android.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/// <reference path="./AndroidPdfViewer.d.ts" />
import pdfviewer = com.github.barteksc.pdfviewer;
import * as fs from 'tns-core-modules/file-system';
import * as http from 'tns-core-modules/http';
import { PDFViewCommon, srcProperty } from './pdf-view.common';
export class PDFView extends PDFViewCommon {
private promise: Promise<void>;
private tempFolder = fs.knownFolders.temp().getFolder('PDFViewer.temp/');
private onLoadHandler = (() => {
const pdfViewRef = new WeakRef(this);
return new pdfviewer.listener.OnLoadCompleteListener({
loadComplete: numPages => {
PDFViewCommon.notifyOfEvent(PDFViewCommon.loadEvent, pdfViewRef);
},
});
})();
public get android() {
return this.nativeView as pdfviewer.PDFView;
}
public set android(value) {
this.nativeView = value;
}
public createNativeView() {
// tslint:disable-next-line:no-unsafe-any
return new pdfviewer.PDFView(this._context, void 0);
}
public [srcProperty.setNative](value: string) {
this.loadPDF(value);
}
public loadPDF(src: string) {
if (!src || !this.android) {
return;
}
// reset any previous promise since we've called loadPDF again
this.promise = void 0;
if (src.indexOf('://') === -1) {
src = 'file://' + src;
} else if (src.indexOf('file://') !== 0) {
// AndroidPdfViewer cannot load from remote URLs, download to cache
this.cacheThenLoad(src);
return;
}
const uri = android.net.Uri.parse(src);
this.android
.fromUri(uri)
.onLoad(this.onLoadHandler)
.load();
}
private cacheThenLoad(url: string) {
// clear everything in cache
this.tempFolder.clear().then(() => {
// download to cache
const promise = this.promise = http
.getFile(url, `${this.tempFolder.path}/${Date.now()}.pdf`)
.then(file => {
if (this.promise === promise) { // make sure we haven't switched
this.loadPDF(file.path);
}
}).catch(error => {
console.error(error);
});
});
}
}