34

I am trying to opening some pdf from my Android application. I am using an Intent for doing that:

Intent intent = new Intent();
intent.setDataAndType(Uri.parse(url), "application/pdf");
startActivity(intent);

This code works well for some pdf but it fails when I try to open others.

This is the message that Android is showing to me:

There is a problem with the file.

I have to mention that the pdf that are being opened without problems are created with one Crystal Report template and the pdfs that are failing are created with another one.

As opposed, if I open the url of the pdfs that are failing on my browser (on my computer), it does not give to me any error opening them so I guess that maybe there is some limitation on Android that differs from some pdf to another (on Crystal Report template) but I cannot see it.

What limitations exist on opening a pdf file on Android? (Size, some parameters of Crystal Report that are not allowed, etc...)

I have discarded that it could be a size limitation because the pdf files that are giving problems are smaller than the files that do not give any error.

Proves I have done:

  • Opening wrong PDFs on browser ~~> OK
  • Downloading wrong PDF on mobile phone and open it ~~> OK
  • Opening wrong PDFs on APP ~~> Error
  • Opening good PDF on APP of the company that PDFs crash ~~> OK

EDIT

I have noticed that I was using http:// protocol but the PDF is on a https:// protocol, so I have changed it on Uri.parse method.

When I made this change, the app crashed and an error was shown on the log:

android.content.ActivityNotFoundException: No Activity found to handle Intent

Also, I have noticed that the PDFs that does not give to me any error, are in an url with http:// protocol instead of https:// so I guess that https:// protocol can be the problem.

Am I only able to open http:// request on an Intent?

16
  • @matrix I have tried using Android 6.0.1 and Android 7.0 and I am getting the same behaviour. Some pdfs are being opened without problems and others are failing when I try to open them so I think that is not a problem with the version, not as with pdf files. Jul 25, 2017 at 8:23
  • Please share sample PDFs which illustrate the issue.
    – mkl
    Jul 25, 2017 at 12:58
  • @mkl I cannot share them because they are bills from my clients so I cannot give their information. Jul 25, 2017 at 13:01
  • @mkl If you need some other data that I can provide please let me know. Jul 25, 2017 at 13:10
  • You appear to have access to the Crystal Report templates that are used to create those problem PDFs. Simply use those templates with dummy data to provide a sample file.
    – mkl
    Jul 25, 2017 at 14:16

9 Answers 9

12
+25

It could be the file failed to be interpret by the Android PDF viewer app. Have you tried to copy/download the exact same file to your Android phone and open from there?

Also, I'd suggest to use IntentChooser for launching the PDF viewer, just to play safe on no PDF viewer installed / giving user option to choose app:

Intent intent = new Intent();
intent.setDataAndType(Uri.parse(url), "application/pdf");
Intent chooserIntent = Intent.createChooser(intent, "Open Report");
startActivity(chooserIntent);
2
  • Thanks for answer but it does not allow me to opening it. If I download it and try to open it, it is opening without problems but it does not allow to me chose between programs when I fire the Intent. Aug 11, 2017 at 9:39
  • 1
    Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW); pdfOpenintent.setDataAndType(path or url , "application/pdf"); Intent intent = Intent.createChooser(pdfOpenintent, "Open File"); startActivity(intent); Aug 23, 2017 at 5:46
10

I found a workaround to view my PDF on my Android application (but does not allow me to download it after show on the application). If I open my PDF using Google Docs I can open it with my Intent.

This is what I had to add before my url:

https://docs.google.com/gview?embedded=true&url=

so the final url will be like:

https://docs.google.com/gview?embedded=true&url=https://myUrl.pdf

Here is the whole code I am using right now:

String url= "https://docs.google.com/gview?embedded=true&url=https://url.pdf";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);

But it is still not enough, because I would like to open it without need of using a third party application. Also, opening PDF with Google Docs is slow and I have to wait too much until the PDF is finally opened.

If anyone knows how to open it with native Android please let me know.


What happens if I do not open it with Google Docs?

With the same code, but just using my url, instead the added Google Docs url, Android let me choose between two applications: Adobe Acrobat Reader and Google Chrome.

  • If I open it with Google Chrome it download the PDF but it is not opened automatically.

  • If I open it with Adobe Acrobat Reader, it gives to me the following error:

    The PDF cannot be shown (it cannot be opened)

3
  • Is it that you want to view the pdf page by page, or possibly extract data from it?
    – AnthonyK
    Aug 20, 2017 at 19:05
  • @TonyKutzler I would like to view the whole PDF. It would be great if the user can also download it, but after view the PDF on the screen. Aug 21, 2017 at 6:03
  • Android has very limited PDF rendering support. However, if you are on minSdk >= 21(Android 5), you may find PdfRenderer class useful: medium.com/@chahat.jain0/… Aug 30, 2019 at 9:55
4

Using an intent to open a pdf file with https:// protocol, definitelly https:// isn´t the problem.

I see that you are trying this method defining the data type:

Intent intent = new Intent();
intent.setDataAndType(Uri.parse(url), "application/pdf");
startActivity(intent);

but it will cause:

ActivityNotFoundException: No Activity found to handle Intent

if you use this other method probably you can´t see PDF readers in the options to open this kind of files:

  Intent intent = new Intent();
  intent.setDataAndType(Uri.parse(url), "application/pdf");
  Intent chooserIntent = Intent.createChooser(intent, "Open Report");
  startActivity(chooserIntent);

You must try this method without the type definition and it will work perfectly:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);

Other cause of this problem opening the pdf file via intent would be the default application to open this kind of files, so probably you will have a corrupt or invalid application configured, so reset the defaults:

Go to Settings. Tap Applications. Tap Default Applications.

Select the app and Clear defaults

2
  • 1
    I have tried the three methods and these are the results: With the first one (the same I was using before) it throws to me the error that I have pointed. With the second one it says: "There is no application available". With the third one, it let me choose between Google Chrome and Adobe Acrobat. If I open it with Google Chrome it starts the download of it and if I open it with Adobe Acrobat it does not me allow to open the PDF, it says: "The PDF cannot be shown (it cannot be opened)". But it only happens with https protocol, when I try to open a PDF with http:// protocol, the PDF opens. Aug 18, 2017 at 7:37
  • Further, I would like to visualice the PDF on my application, not download it at first time. Aug 18, 2017 at 7:39
4

If API >=21 you can use PDFRenderer to create a bitmap of each page, but its only viewable, not editable. Here is an example i made up on the fly, lacking navigation buttons, but those shouldn't be to hard to implement.

PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(new File("/path/to/file.pdf"), 
            ParcelFileDescriptor.MODE_READ_ONLY));
    PdfRenderer.Page page = renderer.openPage(0);
    Bitmap bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(),
            Bitmap.Config.ARGB_8888);
    page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
    imageView.setImageBitmap(bitmap);
    page.close();
    renderer.close();

Edit

PdfRenderer requires a local file for the FileDescriptor. So in turn viewing through the "cloud", to my knowledge, isnt possible with this approach.

2
  • And if I do not have the path of the file, I mean, that the path of the file is an url, can I use it as well? Aug 21, 2017 at 6:02
  • @Error404 Answer Edited
    – AnthonyK
    Aug 21, 2017 at 9:08
4
+50

Simple add following library for android:

//in app level build
compile 'com.joanzapata.pdfview:android-pdfview:1.0.4@aar'

//inside your xml file
<com.joanzapata.pdfview.PDFView
    android:id="@+id/pdfview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

//inside java code
 pdfView.fromAsset(pdfName)
.pages(0, 2, 1, 3, 3, 3)
.defaultPage(1)
.showMinimap(false)
.enableSwipe(true)
.onDraw(onDrawListener)
.onLoad(onLoadCompleteListener)
.onPageChange(onPageChangeListener)
.load();

for more info, use this GitHub link: https://github.com/JoanZapata/android-pdfview

2
  • This would not work for me as I need to load my PDF from an url. The project that you have attached is no longer maintained so it will not be a good solution if it does not have maintenance. Further, the alternative that they recommend have a section Why I cannot open PDF from URL?. Aug 21, 2017 at 10:43
  • yes the above link/library has no maintenance but it is good library to show in-app pdf, other you can use ITEXT pdf library which is paid one, alternatively you can just download the pdf and show it inside your app with this, if you want to go with the url then GOOGLE DRIVE is one of the best. Aug 21, 2017 at 10:49
3

You can use Webview to open PDF from url like this:

webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + your url);
2
  • @Error404 as per your requirement this will also work fine Aug 21, 2017 at 11:22
  • that's not for offline usage am i right @yogesh ?
    – gumuruh
    Mar 13, 2022 at 20:19
2

You can try this,

public void OpenPDFFile(String file_name) {
    try {
        File pdfFile = new File(getFile(), file_name);//File path
        if (pdfFile.exists()) //Checking for the file is exist or not
        {
            Uri path = Uri.fromFile(pdfFile);
            Intent objIntent = new Intent(Intent.ACTION_VIEW);
            objIntent.setDataAndType(path, "application/pdf");
            objIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            try {
                startActivity(objIntent);
                Log.e("IR", "No exception");
            }
            catch (ActivityNotFoundException e) {
                Log.e("IR", "error: " + e.getMessage());
                Toast.makeText(DownloadedPdfActivity.this,
                        "No Application Available to View PDF",
                        Toast.LENGTH_SHORT).show();
            }

        }
    }catch (Exception e){
        e.printStackTrace();
    }
}

or

    mWebviewPdf.getSettings().setJavaScriptEnabled(true);
    mWebviewPdf.getSettings().setLoadWithOverviewMode(true);
    mWebviewPdf.getSettings().setUseWideViewPort(true);
    pDialog = new ProgressDialog(PdfActivity.this, android.R.style.Theme_DeviceDefault_Dialog);
    pDialog.setTitle("PDF");
    pDialog.setMessage("Loading...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    mWebviewPdf.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            pDialog.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            pDialog.dismiss();
        }
    });
    **mWebviewPdf.loadUrl("https://docs.google.com/gview?embedded=true&url=" + mUrl);**


 String url= "https://docs.google.com/gview?embedded=true&url=" + mUrl;
 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
 startActivity(intent);

You can show pdf in webview.

1
  • 1
    what the importance of Intent.FLAG_ACTIVITY_NO_HISTORY ? that doesn't make any changes for opening pdf .... right @Saveen
    – gumuruh
    Mar 13, 2022 at 20:25
2

You can use following library for android:- //in app level build compile

compile 'com.github.barteksc:android-pdf-viewer:2.6.1'

in your xml:

<com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

in your activity/ fragment:

pdfView.fromUri(Uri)
or
pdfView.fromFile(File)
or
pdfView.fromBytes(byte[])
or
pdfView.fromStream(InputStream) // stream is written to bytearray - native code cannot use Java Streams
or
pdfView.fromSource(DocumentSource)
or
pdfView.fromAsset(String)

For more information, refer this link

2
  • But I need to view it from an url and this library has a section Why I cannot open PDF from URL? Aug 22, 2017 at 14:53
  • @Error404: this library provides a feature to load pdf file from URL. you need to pass URI in below method. I have used this library in one of my projects. pdfView.fromUri(Uri)
    – Mehta
    Aug 23, 2017 at 6:59
2

Your problem is that Your pdf is downloading inside the Data/data folder and when you try to open using default intent then external app doesn't have any permissions to open the file from inside the data/data folder so you need to download the file outside directory of the app and then try to reopen it will be working.

3
  • how we can allow the adobe reader app to access file downloaded from my application. It seems that one drive app has no issues to open my pdf file. But adobe reader throw exception "make sure you have internet connection or make the filename shorter"
    – Stelios
    Oct 23, 2020 at 7:38
  • Is their any updates on this i am facing same issue
    – pkgrover
    Dec 4, 2021 at 15:43
  • @pkgrover, Now I have moved the pdf outside the data/data folders for example saving in sdcard or cache where permissions not required specially the cache works great for me. Mar 14, 2022 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.