需要帮助来解决我的问题。在我的 android webview 中,使用tcpdf生成的 pdf无法正常工作......它在 pdf 中生成了一些垃圾值
//下载文件 myWebView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request myRequest = new DownloadManager.Request(Uri.parse(url));
myRequest.allowScanningByMediaScanner();
myRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//new
myRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
//create download manager
DownloadManager myManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
myManager.enqueue(myRequest);
Toast.makeText(MainActivity.this, "Downloding file....", Toast.LENGTH_SHORT).show();
}
});
//TCPDF
myWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//start download
DownloadPDF downlooadPDF = new DownloadPDF();
downlooadPDF.execute(url, userAgent, contentDisposition);
//Toast.makeText(MainActivity.this, "Downloding ...", Toast.LENGTH_SHORT).show();
}
});
}
//TCPDF
private class DownloadPDF extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
File myDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).toString() + "/myPDF");
// create the directory if it does not exist
if (!myDir.exists()) myDir.mkdirs();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.connect();
//get filename from the contentDisposition
String filename = null;
Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(sUrl[2]);
while (m.find()) {
filename = m.group(1);
}
File outputFile = new File(myDir, filename);
InputStream input = new BufferedInputStream(connection.getInputStream());
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
connection.disconnect();
output.flush();
output.close();
input.close();
displayPdf(); // a function to open the PDF file automatically
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void displayPdf() {
try {
Object filename = fileList();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/myPDF/" + filename);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} catch (Exception e) {
Log.i("TAG", e.getMessage());
}
}
}