I want to make an app which show PDF files from server online (Google docs in my case) which I have done using webview here the image how it will be but if user wants to view it offline then I have to give download option so if they press download I wanted to remove"online mode" button so they can view it offline like thisand also an delete option which deletes downloaded file and retain the online mode please help me with code I'm new to android
How to diaplay PDF file online and also an option to download it and view on same activity in my app
Asked
Active
Viewed 45 times
0
-
Bro, have any question , you can ask me – Jun 14 '20 at 10:31
2 Answers
0
You can do it easily
First of all, i recommend you to store your pdf files in google drive, not in google docs. After this, you can download your files from google drive easily.
Download files from Google drive
[https://stackoverflow.com/a/48824834/13651827][1]
Provide offline files
Next, According to you, you want to provide pdf files offline also. To achieve this, first of all, you have to download your file and store it in storage of device of your user. Now, access pdf file from device storage and provide to user even user is offline or online.
0
To display Pdf file in android you can use this library. You will find its usage in their documentation. To download a file you can try in this way
private class PdfDownloader extends AsyncTask<String, Integer, String> {
byte[] pdfFile;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
try {
URL myURL = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection) myURL.openConnection();
connection.setDoInput(true);
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Error";
}
InputStream is = connection.getInputStream();
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int newLength;
while ((newLength = is.read(buffer)) > 0) {
byteArrayOutputStream.write(buffer, 0, newLength);
}
pdfFile = byteArrayOutputStream.toByteArray();
is.close();
return "Success";
} catch (Exception e) {
e.printStackTrace();
return "Error";
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s.equals("Success")) {
try (FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(pdfFile);
}
catch (Exception e){
e.printStackTrace();
}
}
}
}
Then call the AsyncTask using
new PdfDownloader().execute(PdfFileUrl);

MrinmoyMk
- 551
- 7
- 21