[英]How to use Android Download Manager to download PDF generated from link, not direct PDF file path
I have created webview of my website in android app. 我已经在android应用中创建了网站的webview。 I am using Download Manager in Android to download a PDF file from my website. 我正在使用Android中的下载管理器从我的网站下载PDF文件。 But there is not a direct link of PDF file, instead that PDF file is getting Generated and because of that thing, I am not able to download that file. 但是没有PDF文件的直接链接,而是正在生成PDF文件,由于这个原因,我无法下载该文件。 Download is showing Unsuccessful. 下载显示不成功。
My Coding: 我的编码:
myWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
try{
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
if(isExternalStorageWritable() && isExternalStorageReadable()) {
request.setTitle("Invoice");
request.setDescription("Downloads");
request.setVisibleInDownloadsUi(true);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
request.setDestinationInExternalFilesDir(MainActivity.this,Environment.DIRECTORY_DOWNLOADS, "invoice.pdf");//download to internal memory
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "No SD Card Present.."+Environment.DIRECTORY_DOWNLOADS, //To notify the Client that the file is being downloaded
Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
Log.d("Caught inside uri", e.toString());
}
}
});// checks for downloads
To get response use 获得响应使用
val request = InputStreamVolleyRequest(Request.Method.POST, url, object : Response.Listener<ByteArray> {
override fun onResponse(response: ByteArray?) {
Log.d("Response ", response.toString())
//val str = save(response)
abaraResponse.onSuccess(methodName, response)
stopService()
//Log.d("Response ", str)
}
},
object : Response.ErrorListener {
override fun onErrorResponse(error: VolleyError?) {
Log.d("Response ", error.toString())
abaraResponse.onError(methodName, error)
stopService()
}
}, headerMap, body)
Here is input stream request class : 这是输入流请求类:
public class InputStreamVolleyRequest extends Request<byte[]> {
private final Response.Listener<byte[]> mListener;
private Map<String, String> mParams;
private JSONObject mBody;
//create a static map for directly accessing headers
public Map<String, String> responseHeaders ;
public InputStreamVolleyRequest(int method, String mUrl , Response.Listener<byte[]> listener,
Response.ErrorListener errorListener, HashMap<String, String> params, JSONObject body) {
// TODO Auto-generated constructor stub
super(method, mUrl, errorListener);
// this request would never use cache.
setShouldCache(false);
mListener = listener;
mParams=params;
mBody = body;
}
@Override
public byte[] getBody() throws AuthFailureError {
return mBody.toString().getBytes();
}
@Override
public Map<String, String> getHeaders()
throws com.android.volley.AuthFailureError {
return mParams;
};
@Override
protected void deliverResponse(byte[] response) {
mListener.onResponse(response);
}
@Override
protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {
//Initialise local responseHeaders map with response headers received
responseHeaders = response.headers;
//Pass the response data here
return Response.success( response.data, HttpHeaderParser.parseCacheHeaders(response));
}
}
Use following code to get pdf from downloaded bytearray: 使用以下代码从下载的字节数组中获取pdf:
fun save(response: ByteArray?): String {
val path: String = Environment.getExternalStorageDirectory().path + "/" + pdfname+ ".pdf"
var f1 = File(path);
try {
val bos = BufferedOutputStream(FileOutputStream(f1))
bos.write(response)
bos.flush()
bos.close()
} catch (e: FileNotFoundException) {
e.printStackTrace();
} catch (e: IOException) {
e.printStackTrace();
}
return f1.path; // I like to return it because i can use it to start a "open file" intent
}
Then using pdfViewer library set your response to pdf viewer 然后使用pdfViewer库将您的响应设置为pdf查看器
pdfView.fromFile(File(/*from save*/ ))
.defaultPage(1)
.showMinimap(false)
.enableSwipe(true)
.load()
pdf library is compile 'com.joanzapata.pdfview:android-pdfview:1.0.4@aar'
pdf库正在compile 'com.joanzapata.pdfview:android-pdfview:1.0.4@aar'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.