-
Notifications
You must be signed in to change notification settings - Fork 5
/
App.js
242 lines (223 loc) · 7.24 KB
/
App.js
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/**
* Copyright (c) 2020-present, Bouncing Shield (bouncingshield.com)
* All rights reserved.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useEffect, useState } from "react";
import { StyleSheet, Dimensions, View, Text, Image, TouchableOpacity, Platform } from "react-native";
import Pdf from "react-native-pdf";
const RNFS = require("react-native-fs");
import { PDFDocument } from "pdf-lib";
import Signature from "react-native-signature-canvas";
import { decode as atob, encode as btoa } from "base-64"
export default PDFExample = () => {
const sourceUrl = "http://samples.leanpub.com/thereactnativebook-sample.pdf";
const [fileDownloaded, setFileDownloaded] = useState(false);
const [getSignaturePad, setSignaturePad] = useState(false);
const [pdfEditMode, setPdfEditMode] = useState(false);
const [signatureBase64, setSignatureBase64] = useState(null);
const [signatureArrayBuffer, setSignatureArrayBuffer] = useState(null);
const [pdfBase64, setPdfBase64] = useState(null);
const [pdfArrayBuffer, setPdfArrayBuffer] = useState(null);
const [newPdfSaved, setNewPdfSaved] = useState(false);
const [newPdfPath, setNewPdfPath] = useState(null);
const [pageWidth, setPageWidth] = useState(0);
const [pageHeight, setPageHeight] = useState(0);
const [filePath, setFilePath] = useState(`${RNFS.DocumentDirectoryPath}/react-native.pdf`);
useEffect(() => {
this.downloadFile();
if (signatureBase64){
setSignatureArrayBuffer(this._base64ToArrayBuffer(signatureBase64));
}
if (newPdfSaved){
setFilePath(newPdfPath);
setPdfArrayBuffer(this._base64ToArrayBuffer(pdfBase64));
}
console.log('filePath', filePath)
}, [signatureBase64, filePath, newPdfSaved]);
_base64ToArrayBuffer = (base64) => {
const binary_string = atob(base64);
const len = binary_string.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
_uint8ToBase64 = (u8Arr) => {
const CHUNK_SIZE = 0x8000; //arbitrary number
let index = 0;
const length = u8Arr.length;
let result = "";
let slice;
while (index < length) {
slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length));
result += String.fromCharCode.apply(null, slice);
index += CHUNK_SIZE;
}
return btoa(result);
}
downloadFile = () => {
if (!fileDownloaded){
RNFS.downloadFile({
fromUrl: sourceUrl,
toFile: filePath,
}).promise.then((res) => {
setFileDownloaded(true);
this.readFile();
});
}
}
readFile = () => {
RNFS.readFile(`${RNFS.DocumentDirectoryPath}/react-native.pdf`, "base64").then((contents) => {
setPdfBase64(contents);
setPdfArrayBuffer(this._base64ToArrayBuffer(contents));
})
}
getSignature = () => {
setSignaturePad(true);
}
handleSignature = signature => {
setSignatureBase64(signature.replace("data:image/png;base64,", ""));
setSignaturePad(false);
setPdfEditMode(true);
}
handleSingleTap = async (page, x, y) => {
if (pdfEditMode){
setNewPdfSaved(false);
setFilePath(null);
setPdfEditMode(false);
const pdfDoc = await PDFDocument.load(pdfArrayBuffer);
const pages = pdfDoc.getPages();
const firstPage = pages[page - 1]
// The meat
const signatureImage = await pdfDoc.embedPng(signatureArrayBuffer)
if (Platform.OS == 'ios') {
firstPage.drawImage(signatureImage, {
x: ((pageWidth * (x - 12)) / Dimensions.get("window").width),
y: pageHeight - ((pageHeight * (y + 12)) / 540),
width: 50,
height: 50,
})
} else {
firstPage.drawImage(signatureImage, {
x: (firstPage.getWidth() * x ) / pageWidth,
y: (firstPage.getHeight() - ((firstPage.getHeight() * y ) / pageHeight)) - 25,
width: 50,
height: 50,
})
}
// Play with these values as every project has different requirements
const pdfBytes = await pdfDoc.save();
const pdfBase64 = this._uint8ToBase64(pdfBytes);
const path = `${RNFS.DocumentDirectoryPath}/react-native_signed_${Date.now()}.pdf`;
console.log('path', path)
RNFS.writeFile(path, pdfBase64, "base64").then((success) => {
setNewPdfPath(path);
setNewPdfSaved(true);
setPdfBase64(pdfBase64);
})
.catch((err) => {
console.log(err.message);
});
}
}
return (
<View style={styles.container}>
{ getSignaturePad ? (
<Signature
onOK={(sig) => this.handleSignature(sig)}
onEmpty={() => console.log("___onEmpty")}
descriptionText="Sign"
clearText="Clear"
confirmText="Save"
/>
) : ((fileDownloaded) && (
<View>
{ filePath ? (
<View>
<Text style={styles.headerText}>React Native Digital PDF Signature</Text>
<Pdf
minScale={1.0}
maxScale={1.0}
scale={1.0}
spacing={0}
fitPolicy={0}
enablePaging={true}
source={{uri: filePath}}
usePDFKit={false}
onLoadComplete={(numberOfPages, filePath, {width, height})=>{
setPageWidth(width);
setPageHeight(height);
}}
onPageSingleTap={(page, x, y) => {
this.handleSingleTap(page, x, y);
}}
style={styles.pdf}/>
</View>
) : (
<View style={styles.button}>
<Text style={styles.buttonText}>Saving PDF File...</Text>
</View>
)}
{ pdfEditMode ? (
<View style={styles.message}>
<Text>* EDIT MODE *</Text>
<Text>Touch where you want to place the signature</Text>
</View>
) : (filePath && (
<View>
<TouchableOpacity
onPress={this.getSignature}
style={styles.button}
>
<Text style={styles.buttonText}>Sign Document</Text>
</TouchableOpacity>
<View>
<Image
source={{uri: "http://www.bouncingshield.com/icons/icon-512x512.png"}}
style={{width: 40, height: 40, alignSelf: "center"}}
/>
<Text style={styles.headerText}>bouncingshield.com</Text>
</View>
</View>
))}
</View>
))}
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#f4f4f4"
},
headerText: {
color: "#508DBC",
fontSize: 20,
marginBottom: 20,
alignSelf: "center"
},
pdf: {
width: Dimensions.get("window").width,
height: 540,
},
button: {
alignItems: "center",
backgroundColor: "#508DBC",
padding: 10,
marginVertical: 10
},
buttonText: {
color: "#DAFFFF",
},
message: {
alignItems: "center",
padding: 15,
backgroundColor: "#FFF88C"
}
});