我在mWebView中调用URL时尝试加载base64 String作为参数。
mWebView.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=data:application/pdf;base64," + pdfString);
在PDF.js的帮助下将其呈现为PDF文件pdfString
是将PDF转换为base64字符串。
在Chrome中调试webView时 - > delevopler工具 - >远程设备 - >检查 - > 我收到以下错误:
XMLHttpRequest无法加载数据:application / pdf; base64,..... Cross 原始请求仅支持HTTP。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebChromeClient (new WebChromeClient());
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
mWebView.setWebContentsDebuggingEnabled(true);
String path = Environment.getExternalStorageDirectory().toString() + "/Download/income_tax_return.pdf";
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String pdfString = Base64.encodeToString(bytes, Base64.NO_WRAP);
mWebView.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=data:application/pdf;base64," + pdfString);
}