14
14
import android .webkit .WebViewClient ;
15
15
16
16
import java .io .File ;
17
+ import android .util .Base64 ;
18
+ import java .io .IOException ;
19
+ import java .io .RandomAccessFile ;
20
+
21
+ import com .facebook .react .bridge .Promise ;
22
+ import com .facebook .react .bridge .WritableMap ;
17
23
18
24
/**
19
25
* Converts HTML to PDF.
@@ -32,6 +38,9 @@ public class PdfConverter implements Runnable {
32
38
private PrintAttributes mPdfPrintAttrs ;
33
39
private boolean mIsCurrentlyConverting ;
34
40
private WebView mWebView ;
41
+ private boolean mShouldEncode ;
42
+ private WritableMap mResultMap ;
43
+ private Promise mPromise ;
35
44
36
45
private PdfConverter () {
37
46
}
@@ -58,7 +67,19 @@ public void onPageFinished(WebView view, String url) {
58
67
documentAdapter .onWrite (new PageRange []{PageRange .ALL_PAGES }, getOutputFileDescriptor (), null , new PrintDocumentAdapter .WriteResultCallback () {
59
68
@ Override
60
69
public void onWriteFinished (PageRange [] pages ) {
61
- destroy ();
70
+ try {
71
+ String base64 = "" ;
72
+ if (mShouldEncode ) {
73
+ base64 = encodeFromFile (mPdfFile );
74
+ }
75
+ mResultMap .putString ("filePath" , mPdfFile .getAbsolutePath ());
76
+ mResultMap .putString ("base64" , base64 );
77
+ mPromise .resolve (mResultMap );
78
+ } catch (IOException e ) {
79
+ mPromise .reject (e .getMessage ());
80
+ } finally {
81
+ destroy ();
82
+ }
62
83
}
63
84
});
64
85
}
@@ -75,7 +96,7 @@ public void setPdfPrintAttrs(PrintAttributes printAttrs) {
75
96
this .mPdfPrintAttrs = printAttrs ;
76
97
}
77
98
78
- public void convert (Context context , String htmlString , File file ) {
99
+ public void convert (Context context , String htmlString , File file , boolean shouldEncode , WritableMap resultMap , Promise promise ) {
79
100
if (context == null )
80
101
throw new IllegalArgumentException ("context can't be null" );
81
102
if (htmlString == null )
@@ -90,6 +111,9 @@ public void convert(Context context, String htmlString, File file) {
90
111
mHtmlString = htmlString ;
91
112
mPdfFile = file ;
92
113
mIsCurrentlyConverting = true ;
114
+ mShouldEncode = shouldEncode ;
115
+ mResultMap = resultMap ;
116
+ mPromise = promise ;
93
117
runOnUiThread (this );
94
118
}
95
119
@@ -126,5 +150,15 @@ private void destroy() {
126
150
mPdfPrintAttrs = null ;
127
151
mIsCurrentlyConverting = false ;
128
152
mWebView = null ;
153
+ mShouldEncode = false ;
154
+ mResultMap = null ;
155
+ mPromise = null ;
156
+ }
157
+
158
+ private String encodeFromFile (File file ) throws IOException {
159
+ RandomAccessFile randomAccessFile = new RandomAccessFile (file , "r" );
160
+ byte [] fileBytes = new byte [(int )randomAccessFile .length ()];
161
+ randomAccessFile .readFully (fileBytes );
162
+ return Base64 .encodeToString (fileBytes , Base64 .DEFAULT );
129
163
}
130
164
}
0 commit comments