1

I want to load a pdf file from external storage (Download/Pdfs/myfile.pdf) using AndroidPdfViewer but it shows blank screen without any error. I tried lots of ways but it's not working.

public class PdfViewActivity2 extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        File path = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/Pdfs/myfile.pdf");
        PDFView pdfView = findViewById(R.id.pdfView);
        pdfView.fromFile(path).load();

I have a pdf file in my "Download/Pdfs/myfile.pdf" and i used the above code to load the file but it's not working. I have given storage permission manually from settings. Can anyone please correct me where i am making a mistake.

Gopal Meena
  • 407
  • 8
  • 20

4 Answers4

0

First, add the library to your build.gradle file

implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

To open a PDF file from storage, use this code. There are comments that explain what it does.

public class PdfViewActivity2  extends AppCompatActivity {

    // Declare PDFView variable
    private PDFView pdfView;
    private final int PDF_SELECTION_CODE = 99;

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

        // Initialize it
        pdfView = findViewById(R.id.pdfView);

        // Select PDF from storage
        // This code can be used in a button
        Toast.makeText(this, "selectPDF", Toast.LENGTH_LONG).show();
        Intent browseStorage = new Intent(Intent.ACTION_GET_CONTENT);
        browseStorage.setType("application/pdf");
        browseStorage.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(Intent.createChooser(browseStorage, "Select PDF"), PDF_SELECTION_CODE);
    }


    // Get the Uniform Resource Identifier (Uri) of your data, and receive it as a result.
    // Then, use URI as the pdf source and pass it as a parameter inside this method fromUri(Uri uri)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PDF_SELECTION_CODE && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedPdfFromStorage = data.getData();
            pdfView.fromUri(selectedPdfFromStorage).defaultPage(0).load();
        }
    }
}
Marwa Eltayeb
  • 1,921
  • 1
  • 17
  • 29
  • Thanks for the answer but bro i don't want to select the pdf file, i have a specified file path and i want to load load it when somebody open's my app. – Gopal Meena Dec 29 '20 at 13:31
0

In an Android 10 device your app has no access to external storage.

Unless you add

android:requestLegacyExternalStorage="true"

in application tag of manifest file.

blackapps
  • 8,011
  • 2
  • 11
  • 25
0

Instead of using fromFile() use fromSource(). i.e. Declare pathe as DocumentSource instead of File.

public class PdfViewActivity2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    DocumentSource path = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/myfile.pdf");
    PDFView pdfView = findViewById(R.id.pdfView);
    pdfView.fromSource(path).load();
0

I have tested your code and it works just fine on Android 10 device. Your are missing something from the below:

1.In Android Manifest File add the READ_EXTERNAL_STORAGE permission

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

and inside application tag add requestLegacyExternalStorage to true to be able to have access on External Storage on Android 10 device and above.

<application
        android:requestLegacyExternalStorage="true"

2.Verify that the pdf exists on the device under "/Download/Pdfs/myfile.pdf" path.

3.Change your activity using the below code by requesting External Storage permission at runtime first in onCreate method:

public class PdfViewActivity2 extends AppCompatActivity {

    private static final int READ_STORAGE_PERMISSION_REQUEST_CODE = 1000;

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

        //check if Read External Storage permission was granded
        boolean granded = checkPermissionForReadExtertalStorage();
        if(!granded){
            requestPermissionForReadExtertalStorage();
        }
        else {
           readPdf();
        }
    }

    public boolean checkPermissionForReadExtertalStorage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int result = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            return result == PackageManager.PERMISSION_GRANTED;
        }
        return false;
    }

    public void requestPermissionForReadExtertalStorage() {
        try {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_STORAGE_PERMISSION_REQUEST_CODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case READ_STORAGE_PERMISSION_REQUEST_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted. Read Pdf from External Storage
                    readPdf();
                } else {
                    // permission denied. Disable the functionality that depends on this permission.
                }
            }
        }
    }

    private void readPdf(){
        File path = new File(Environment.getExternalStorageDirectory().getPath() + "/Download/Pdfs/myfile.pdf");
        PDFView pdfView = findViewById(R.id.pdfView);
        pdfView.fromFile(path).load();
    }
}
MariosP
  • 8,300
  • 1
  • 9
  • 30