[Function] needs webview page loaded, use the file jsPdf or jsExcel generated, downloaded to the phone to save through webview.
[Realize] thinking
① Can you use webView.setDownloadListener achieve?
The answer is: NO, downloadListener required file download link, generated by the front end of the link file does not exist.
② acquiring data file generated corresponding files then generated java
Is not realistic, it is too much trouble, trouble to want to give up.
③ Final Program: base64 encoded by js files and base64 decoding the generated java file!
Ideas: Web pages generated by jsPdf pdf file --js get file base64 code - by interacting with webview js, passed base64 encoding to use java webview-- decoding base64 and writes files to the phone
【Code】
①webview add js call permissions
webView=(WebView)findViewById(R.id.mWebView);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(webChromeClient);
// 设置可以支持缩放
webView.getSettings().setSupportZoom(true);
// 设置出现缩放工具
webView.getSettings().setBuiltInZoomControls(true);
//扩大比例的缩放
webView.getSettings().setUseWideViewPort(true);
//自适应屏幕
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
webView.getSettings().setLoadWithOverviewMode(true);
② Implementation and interaction code js
class decodeInterface {
@RequiresApi(api = Build.VERSION_CODES.O)
@JavascriptInterface
public void decoderBase64File(String base64Code) throws IOException {
Log.e("tag", "decoderBase64File: 被调用"+base64Code );
String savePath= Config.filePath+"pdfDoc.pdf";
byte[] xml=base64Code.getBytes("UTF-8");
byte[] buffer = android.util.Base64.decode(base64Code, Base64.NO_WRAP);
// byte[] buffer= Base64.getDecoder().decode(base64Code);
for (int i = 0; i <buffer.length ; i++) {
if (buffer[i] < 0) {
buffer[i] += 256;
}
}
FileOutputStream out = new FileOutputStream(savePath);
out.write(buffer);
out.close();
}
}
//绑定
webView.addJavascriptInterface(new decodeInterface(),"wv");
③ about how to obtain base64 encoded jsPdf
pdf.addHTML(document.getElementById("saveBox"),options,function() {
pdf.save('report.pdf');
var datauri = pdf.output('dataurlstring');
console.log(datauri);
var base64 = datauri.substring(28);
wv.decoderBase64File(base64);//调用webview方法
});
[Summary] This article only provides an idea using base64 encoded file to transfer files, webview with js interaction code as a bridge.