2

I am trying to open PDF files from external URL. The code is the next:

private void cargaPdf(Uri url){
    //File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
    Intent target = new Intent(Intent.ACTION_VIEW);
    target.setDataAndType(url,"application/pdf");
    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

    Intent intent = Intent.createChooser(target, "Open File");
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        // Instruct the user to install a PDF reader here, or something
    }
}

I have installed adobe and google PDF viewer but when i push the buttom that calls "cargaPdf(Uri url)" function with this url(as you can see is a pdf file):

Uri.parse(https://dl.dropboxusercontent.com/s/oulzgpgnq2ca1ly/KorfbalSpa.pdf?dl=0);

It appears in the screen in spanish "Open File Ninguna aplicacion puede realizar esta accion" or english "Open file No apps can perform this action". What happen?

Edit 1: Ok, now i know that i have to download the file to see it, so, i did this code in the activity:

public void cargaDescripcion(View view){
    Log.d("CargaDescripcion", "Antes del directorio");
    String extStorageDirectory = Environment.getExternalStorageDirectory()
            .toString();
    File folder = new File(extStorageDirectory, "Mypdf");
    folder.mkdir();
    File file = new File(folder, "Read.pdf");
    try {
        file.createNewFile();
        Log.d("CargaDescripcion", "File creado");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    Downloader.DownloadFile(deporte.getUrlDescEs(), file);
    Log.d("CargaDescripcion", "Despues de descargarlo");
    showPdf();
    //folder.delete();
}

public void showPdf()
{
    Log.d("showPdf", "Entramos en show pdf");
    File file = new File(Environment.getExternalStorageDirectory()+"/Mypdf/Read.pdf");
    PackageManager packageManager = getPackageManager();
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    testIntent.setType("application/pdf");
    List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(file);
    intent.setDataAndType(uri, "application/pdf");
    startActivity(intent);
    //file.delete();
}

And this class for download the pdf:

public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
    try {
        FileOutputStream f = new FileOutputStream(directory);
        URL u = new URL(fileURL);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();
        InputStream in = c.getInputStream();
        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

I got it from here Opening pdf file from server using android intent

Edit 2: Now this is the code which download and shows the file:

public void cargaDescripcion(View view){
    download(deporte.getUrlDescEs());
    showPdf();
    //folder.delete();
}

public void download(String url)
{
    new DownloadFile().execute(url, "read.pdf");
}

public void showPdf()
{
    File pdfFile = new File(Environment.getExternalStorageDirectory() + "/Mypdf/" + "read.pdf");  // -> filename = maven.pdf
    Uri path = Uri.fromFile(pdfFile);
    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
    pdfIntent.setDataAndType(path, "application/pdf");
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    try{
        startActivity(pdfIntent);
    }catch(ActivityNotFoundException e){
        Toast.makeText(SelectedSportActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
    }
}
private class DownloadFile extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... strings) {
        String fileUrl = strings[0];   // -> url del archivo
        String fileName = strings[1];  // -> nombre del archivo.pdf
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        File folder = new File(extStorageDirectory, "Mypdf");
        folder.mkdir();

        File pdfFile = new File(folder, fileName);

        try{
            pdfFile.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        Downloader.downloadFile(fileUrl, pdfFile);
        return null;
    }
}

However, the file system is not created by app and file is not downloaded before the app arrives to the next point, that it is "show". So, the file does not exists when the app looks for it.

Edit 3: to SOLVE the show problem i used onPostExecute of asynctask method:

@Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        showPdf();
    }
Community
  • 1
  • 1
Asier
  • 461
  • 9
  • 19

1 Answers1

6

Use this code, this works for me for local file.

resumePdfFile is file path, where your file is saved.

private void openPDF(String resumePdfFile) {
    //file should contain path of pdf file

    Uri path = Uri.fromFile(resumePdfFile);
    Log.e("create pdf uri path==>", "" + path);
    try {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    } catch (ActivityNotFoundException e) {
        Toast.makeText(getApplicationContext(),
                "There is no any PDF Viewer",
                Toast.LENGTH_SHORT).show();
        finish();
    }
}

You can view or download the pdf files by two ways i.e by opening it in device default browser or in the webview by embedding it in your app.

To open the pdf in browser,

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);

To open in webview,

Webview webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(pdf_url);
Bhoomika Patel
  • 1,895
  • 1
  • 13
  • 30
  • You can view or download the pdf by either of the two ways i.e by opening it in default device browser or in the webview by embedding it in your app. see my edited answer. – Bhoomika Patel Jan 08 '17 at 11:32
  • Ok, i have seen that i need download the flie to see it or use your two ways. Thanks i will try. – Asier Jan 08 '17 at 11:39
  • Hi again, now i can open the files but they are empty. I have edited the question with the code. – Asier Jan 08 '17 at 12:18
  • Refer this link: http://stackoverflow.com/questions/24740228/android-download-pdf-from-url-then-open-it-with-a-pdf-reader – Bhoomika Patel Jan 08 '17 at 12:24
  • Thanks! How could i "pause" the app to give time to download the file and create the directories? Because, meanwhile the app downloads the document in background and create the file directory system, keeps running and can not find the directory. – Asier Jan 08 '17 at 12:53
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/132620/discussion-between-bhoomika-patel-and-asier). – Bhoomika Patel Jan 08 '17 at 13:03