Search code examples
androidpdfassetsandroid-assets

Android read pdf file from asset folder


I try to read a pdf file store in the assets folder. I see this solution : Read a pdf file from assets folder

But like comments say this it's not working anymore, the file cannot be found, is there another solution for read a pdf file directly, without copy pdf in external storage ? And I don't want to use PdfRenderer my minimal API is 17


Solution

  • Maybe this can be helpful for somebody so I post my answer :

    private void openPdf(String pdfName){
        AssetManager assetManager = getAssets();
    
        InputStream in = null;
        OutputStream out = null;
        File file = new File(getFilesDir(), pdfName);
        try
        {
            in = assetManager.open(pdfName);
            out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
    
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1)
            {
                out.write(buffer, 0, read);
            }
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e)
        {
            Log.e("tag", e.getMessage());
        }
    
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.parse("file://" + getFilesDir() + "/"+pdfName),
                "application/pdf");
    
        startActivity(intent);
    }
    

    The pdf file is store inside the assets folder