Android download pdf file from url and save to internal storage GitHub

1,Integrate PDF Viewer Library in Gradle file.

implementation ‘com.github.barteksc:android-pdf-viewer:2.8.2’

2,Design Screen as Per Requirement.

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”>
<com.github.barteksc.pdfviewer.PDFView
android:id=”@+id/pdfView”
android:layout_width=”match_parent”
android:layout_height=”match_parent” />
</LinearLayout>

3,Download PDF and View File in PDF viewer.

`public class PdfViewActivity extends AppCompatActivity { 
ActivityPdfviewBinding binding;
ProgressDialog mProgressDialog;
public Context context;
public String samplePDF = "http://www.africau.edu/images/default/sample.pdf";
public static final int PERMISSIONS_MULTIPLE_REQUEST_CERTIFICATE = 123;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_pdfview);
context = PdfViewActivity.this;
mProgressDialog = new ProgressDialog(context);
checkAndroidVersionCertificate();
}
private void downloadFile() {
mProgressDialog.show();
mProgressDialog.setMessage("downloading");
mProgressDialog.setMax(100);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
DownloadFileTask task = new DownloadFileTask( PdfViewActivity.this, samplePDF, "/download/pdf_file.pdf");
task.startTask();
}
public class DownloadFileTask {
public static final String TAG = "DownloadFileTask";
private PdfViewActivity context;
private GetTask contentTask;
private String url;
private String fileName;
public DownloadFileTask(PdfViewActivity context, String url, String fileName) {
this.context = context;
this.url = url;
this.fileName = fileName;
}
public void startTask() {
doRequest();
}
private void doRequest() {
contentTask = new GetTask();
contentTask.execute();
}
private class GetTask extends AsyncTask < String, Integer, String > {
@Override protected String doInBackground(String… arg0) {
int count;
try {
URL _url = new URL(url);
URLConnection conection = _url.openConnection();
conection.connect();
String extension = url.substring(url.lastIndexOf('.') + 1).trim();
InputStream input = new BufferedInputStream(_url.openStream(), 8192);
OutputStream output = new FileOutputStream( Environment.getExternalStorageDirectory() + fileName);
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onPostExecute(String data) {
context.onFileDownloaded();
}
}
}
public void onFileDownloaded() {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
File file = new File(Environment.getExternalStorageDirectory() .getAbsolutePath() + "/download/pdf_file.pdf");
if (file.exists()) {
binding.pdfView.fromFile(file) //.pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
.enableSwipe(true) .swipeHorizontal(true) .enableDoubletap(true) .defaultPage(0) .enableAnnotationRendering(true) .password(null) .scrollHandle(null) .onLoad(new OnLoadCompleteListener() {
@Override public void loadComplete(int nbPages) {
binding.pdfView.setMinZoom(1 f);
binding.pdfView.setMidZoom(5 f);
binding.pdfView.setMaxZoom(10 f);
binding.pdfView.zoomTo(2 f);
binding.pdfView.scrollTo(100, 0);
binding.pdfView.moveTo(0 f, 0 f);
}
}) .load();
}
}
@RequiresApi(api = Build.VERSION_CODES.M) private void checkPermission_Certificate() {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat .checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale ((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale ((Activity) context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
requestPermissions( new String[] {
Manifest.permission .READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSIONS_MULTIPLE_REQUEST_CERTIFICATE);
} else {
requestPermissions( new String[] {
Manifest.permission .READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSIONS_MULTIPLE_REQUEST_CERTIFICATE);
}
} else { // write your logic code if permission already granted
if (!samplePDF.equalsIgnoreCase("")) {
downloadFile();
}
}
}
private void checkAndroidVersionCertificate() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermission_Certificate();
} else {
if (!samplePDF.equalsIgnoreCase("")) {
downloadFile();
}
}
}
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSIONS_MULTIPLE_REQUEST_CERTIFICATE:
if (grantResults.length > 0) {
boolean writePermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (writePermission && readExternalFile) {
if (!samplePDF.equalsIgnoreCase("")) {
downloadFile();
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(permissions[0])) {
Intent intent = new Intent();
intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
} else {
requestPermissions( new String[] {
Manifest.permission .READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSIONS_MULTIPLE_REQUEST_CERTIFICATE);
}
}
}
break;
}
}
}`

How do I save a PDF to internal storage on Android?

Save a PDF of your file on your mobile device.
Open the file that you want to save as a PDF, and then tap File on your tablet or tap the File icon. ... .
On the File tab, tap Print..
If not already selected, tap Save as PDF on the drop-down list, and then tap Save..
Tap Save..

How to download PDF file using URL in Android?

Step by Step Implementation.
Step 1: Create a New Project. ... .
Step 2: Add dependency to build.gradle(Module:app) ... .
Step 3: Add permission to the internet in your AndroidManifest.xml file. ... .
Step 4: Working with the activity_main.xml file. ... .
Step 5: Working with the MainActivity.java file..

How to download file from URL in android programmatically?

In this article, we are going to learn how to download files from an URL using Download Manager. ... .
Step 1: Create a New Project. ... .
Step 2: Grant internet permission in the AndroidManifest.xml file. ... .
Navigate to the app > res > layout > activity_main. ... .
Go to the MainActivity. ... .
Output:.

How do I download a PDF file from my Android app?

How to download a PDF on your Android..
Open the file you want to save as a PDF..
Tap File on your Android, then select Print..
Select from the dropdown menu and click Save as PDF, then click Save..
Pick your preferred location for your PDF and press Save..