60

I'm trying to launch an Intent to open a pdf inside my assets folder in my app. I've read dozens of posts but am still stuck. Apparently I need to copy the pdf to the sd card first then launch an Intent. It still doesn't work.

I think the problem is the Intent launching so I'm simply trying to open a file "example.pdf" that I copied onto the SD card using this code:

Log.w("IR", "TRYING TO RENDER: " + Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf"), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

try {
    startActivity(intent);
    Log.e("IR", "No exception");
} 
catch (ActivityNotFoundException e) {
    Log.e("IR", "error: " + e.getMessage());
    Toast.makeText(InvestorRelations.this, 
        "No Application Available to View PDF", 
        Toast.LENGTH_SHORT).show();
}

This is my LogCat output.

05-10 10:35:10.950: W/IR(4508): TRYING TO RENDER: /mnt/sdcard/example.pdf
05-10 10:35:10.960: E/IR(4508): No exception

Except when this code is run, I get the following Toast (not produced by my app)

"Not a supported document type"

But I can open the document manually through the PDF viewing app installed. Any help would be hugely appreciated.

6 Answers 6

129

Try this code, display pdf file From /sdcard

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
6
  • 2
    Thanks for ending my search. Why does that work though rather than parsing the url from a String?
    – Mike T
    May 10, 2012 at 8:59
  • 1
    How can i move to direct particular page? is there any way? Nov 11, 2013 at 13:32
  • @PratikButani - As you are using third party pdf application to open pdf file you can not handle page navigation in pdf for any particular page.
    – user370305
    Nov 11, 2013 at 14:04
  • Yes,you are right but if i want to use built in viewer then?? @user370305 Nov 12, 2013 at 4:21
  • 4
    Info for FLAG_ACTIVITY_NO_HISTORY here: developer.android.com/reference/android/content/…
    – Rock Lee
    Aug 1, 2016 at 22:14
32

For Android Nougat and above some more work have to be done otherwise the app won't be able to open the .pdf file. We have to set a temporary permission to URI using the FileProvider:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
     File file=new File(mFilePath);
     Uri uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file);
     intent = new Intent(Intent.ACTION_VIEW);
     intent.setData(uri);
     intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
     startActivity(intent);
 } else {
     intent = new Intent(Intent.ACTION_VIEW);
     intent.setDataAndType(Uri.parse(mFilePath), "application/pdf");
     intent = Intent.createChooser(intent, "Open File");
     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     startActivity(intent);
 }
3
  • 1
    +1 from my side. For those who are not getting pdf path from Uri.parse() can use intent.setDataAndType(Uri.fromFile(file), "application/pdf");
    – Radhey
    Sep 13, 2018 at 6:11
  • This answer is not complete you have to define provider in manifest too...
    – Renetik
    Oct 28, 2020 at 20:30
  • Even though you did not add the changes needed to set up the provider, this answer finally solved my issues. I've been looking into it for quite a few hours now and you've solved it! Thank you! My particular situation is an application which targets an old sdk, it's installed manually so I don't need to target API 30+ and it seems the issue was indeed the need to go through the Provider.
    – George
    Apr 3, 2022 at 22:47
3

Download source code from here (Open pdf file from sdcard in android programmatically)

Add this dependency:

compile ‘com.github.barteksc:android-pdf-viewer:2.0.3’

activity_main.xml:

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:id=”@+id/activity_main”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”#efefef”>

<ListView
android:layout_width=”match_parent”
android:id=”@+id/lv_pdf”
android:divider=”#efefef”
android:layout_marginLeft=”10dp”
android:layout_marginRight=”10dp”
android:layout_marginTop=”10dp”
android:layout_marginBottom=”10dp”
android:dividerHeight=”5dp”
android:layout_height=”wrap_content”>

</ListView>
</RelativeLayout>

MainActivity.java:

package com.pdffilefromsdcard;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {

ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();

}

private void init() {

lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra(“position”, i);
startActivity(intent);

Log.e(“Position”, i + “”);
}
});
}

public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {

if (listFile[i].isDirectory()) {
getfile(listFile[i]);

} else {

boolean booleanpdf = false;
if (listFile[i].getName().endsWith(“.pdf”)) {

for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {

}
}

if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);

}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);

}
} else {
boolean_permission = true;

getfile(dir);

obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);

}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {

if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

boolean_permission = true;
getfile(dir);

obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);

} else {
Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show();

}
}
}

}

activity_pdf.xml:

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”match_parent”
android:background=”#ffffff”
android:layout_height=”match_parent”
android:orientation=”vertical”>

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

PdfActivity.java:

package com.pdffilefromsdcard;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import java.io.File;
import java.util.List;

public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener {

PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG=”PdfActivity”;
int position=-1;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}

private void init(){
pdfView= (PDFView)findViewById(R.id.pdfView);
position = getIntent().getIntExtra(“position”,-1);
displayFromSdcard();
}

private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();

pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)

.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
@Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount));
}
@Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), “-“);

}

public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {

Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx()));

if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + “-“);
}
}
}
}

Thanks!

3

The accepted answer is outdated now. Use FileProvider for file sharing.

0
2

This code allow to pickup a pdf file from your SD card

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, 200);
0

It may have something to do with the fact that files in the assets folder get compressed.

Try moving it to your res/raw/ folder.

More info: https://stackoverflow.com/a/4432804/413127

1
  • I'm not even trying to view the pdf for my app any more. I used my OS to copy a pdf to the sdcard and I still can't view it via an Intent
    – Mike T
    May 10, 2012 at 8:51

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.