Read a pdf file from assets folder

android open pdf from assets in webview
open pdf file from raw folder in android
how to upload pdf file in android programmatically
how to open pdf file from assets in android programmatically
how to get the path of selected pdf/doc from file manager in android programmatically
how to download pdf file in android programmatically
how to open pdf file in android application example
android pdf viewer from url
public void DOCS(View btnDocs)
{   
    File fileBrochure = new File("android.resource://com.project.datastructure/assets/abc.pdf");
    if (!fileBrochure.exists())
    {
         CopyAssetsbrochure();
    } 

    /** PDF reader code */
    File file = new File("android.resource://com.project.datastructure/assets/abc.pdf");        

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file),"application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try 
    {
        getApplicationContext().startActivity(intent);
    } 
    catch (ActivityNotFoundException e) 
    {
         Toast.makeText(Stack_dr.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
    }
}
private void CopyAssetsbrochure() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try 
    {
        files = assetManager.list("");
    } 
    catch (IOException e){}
    for(int i=0; i<files.length; i++)
    {
        String fStr = files[i];
        if(fStr.equalsIgnoreCase("abc.pdf"))
        {
            InputStream in = null;
            OutputStream out = null;
            try 
            {
              in = assetManager.open(files[i]);
              out = new FileOutputStream("/sdcard/" + files[i]);
              copyFile(in, out);
              in.close();
              in = null;
              out.flush();
              out.close();
              out = null;
              break;
            } 
            catch(Exception e){}
        }
    }
}

 private void copyFile(InputStream in, OutputStream out) throws IOException 
  {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

I am trying to read a pdf file from assets folder which is present in my application folder . Everything is working perfectly when i click on my DOCS button a pop up comes to let me choose an application for opening the pdf i.e "abc.pdf" but after selecting an option i get an error message "The file path is not valid". I think their is some problem with the path which i have specified in the code. please help

Try this

public class SampleActivity extends Activity
    {

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

        }

        private void CopyReadAssets()
        {
            AssetManager assetManager = getAssets();

            InputStream in = null;
            OutputStream out = null;
            File file = new File(getFilesDir(), "abc.pdf");
            try
            {
                in = assetManager.open("abc.pdf");
                out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

                copyFile(in, out);
                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() + "/abc.pdf"),
                    "application/pdf");

            startActivity(intent);
        }

        private void copyFile(InputStream in, OutputStream out) throws IOException
        {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1)
            {
                out.write(buffer, 0, read);
            }
        }

    }

Make sure to include

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

in manifest

How to open a pdf stored either in res/raw or assets folder , I have read that it might be possible to do this by adding the pdf file to a res/raw folder and read it from there, but i get project errors when i put the pdf file there. Convert Docs & Images to PDF Files Quickly and Easily w/ Acrobat DC. Free Trial!

You can do it like this (tested and working on API 27)

Step 1

Add following dependency in your app gradle:

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

Step 2

Add following XML code:

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

Step 3

Add following code in your java file:

public class MainActivity extends AppCompatActivity {

    PDFView pdfView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pdfView=findViewById(R.id.pdfv);
        pdfView.fromAsset("filename.pdf").load();
    }
}

These changes will load a PDF file on creation of your activity.

Android beginner point: How to Read PDF file Via Assets Folder In , In this tutorial explain how to read pdf file assets folder. I have used PDF Read Library . Step 1. Create Android Project. Step 2. Add Permission in  If you want to open a .pdf file that is stored locally in the assets folder without using an Intent to launch an external app, I suggest using the Android class PdfRenderer. Documentation found here. This is a good example that worked for me. However, this example wouldn't run when I downloaded it.

Though this has been answered, I wanted to share my solution as I think it is a bit easier to include.

Usage:

new OpenLocalPDF(context, 'nameOfPDFStoredInAssets').execute()

And here is the OpenLocalPDF class:

public class OpenLocalPDF {

    private static String TAG = OpenLocalPDF.class.getSimpleName();

    private WeakReference<Context> contextWeakReference;
    private String fileName;

    public OpenLocalPDF(Context context, String fileName) {
        this.contextWeakReference = new WeakReference<>(context);
        this.fileName = fileName.endsWith("pdf") ? fileName : fileName + ".pdf";
    }

    public void execute() {

        Context context = contextWeakReference.get();
        if (context != null) {
            new CopyFileAsyncTask().execute();
        }

    }


    private class CopyFileAsyncTask extends AsyncTask<Void, Void, File> {


        final String appDirectoryName = BuildConfig.APPLICATION_ID;
        final File fileRoot = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), appDirectoryName);

        @Override
        protected File doInBackground(Void... params) {

            Context context = contextWeakReference.get();

            AssetManager assetManager = context.getAssets();

            File file = new File(fileRoot, fileName);

            InputStream in = null;
            OutputStream out = null;
            try {

                file.mkdirs();

                if (file.exists()) {
                    file.delete();
                }

                file.createNewFile();


                in = assetManager.open(fileName);
                Log.d(TAG, "In");

                out = new FileOutputStream(file);
                Log.d(TAG, "Out");

                Log.d(TAG, "Copy file");
                copyFile(in, out);

                Log.d(TAG, "Close");
                in.close();

                out.flush();
                out.close();

                return file;
            } catch (Exception e)
            {
                Log.e(TAG, e.getMessage());
            }

            return null;
        }

        private void copyFile(InputStream in, OutputStream out) throws IOException
        {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1)
            {
                out.write(buffer, 0, read);
            }
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);

            Context context = contextWeakReference.get();


            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(
                    Uri.fromFile(file),
                    "application/pdf");

            context.startActivity(intent);

        }
    }
}

add this permission in Manifest.xml

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

How To View PDF File In Assets Folder, pdf file saved in the assets folder. The purpose is to allow users to view the .pdf file when they select 'menu' from their phones to read the  Firstly, we will look upon how to view PDF, stored in the Assets Folder. Creating an assets folder. Create an assets folder by right-clicking on main > New Folder > Assets Folder and paste the PDF document into it. PDF file name: MindOrks_Android_Online_Professional_Course-Syllabus.pdf. Create getPdfNameFromAssets() method

like say sunsil, but in the case for external directory.

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class MainActivity extends Activity {

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

        copyReadAssets();
    }


    private void copyReadAssets()
    {
        AssetManager assetManager = getAssets();

        InputStream in = null;
        OutputStream out = null;

        String strDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ File.separator + "Pdfs";
        File fileDir = new File(strDir);
        fileDir.mkdirs();   // crear la ruta si no existe
        File file = new File(fileDir, "example2.pdf");



        try
        {

            in = assetManager.open("example.pdf");  //leer el archivo de assets
            out = new BufferedOutputStream(new FileOutputStream(file)); //crear el archivo


            copyFile(in, out);
            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://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + "Pdfs" + "/example2.pdf"), "application/pdf");
        startActivity(intent);
    }

    private void copyFile(InputStream in, OutputStream out) throws IOException
    {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1)
        {
            out.write(buffer, 0, read);
        }
    }
}

change parts of code like these:

out = new BufferedOutputStream(new FileOutputStream(file));

the before example is for Pdfs, in case of to example .txt

FileOutputStream fos = new FileOutputStream(file);

How to open a PDF file in Android programmatically?, So, you can put that document in the assets folder and use it. So, we will look upon all these ways of viewing the PDF in your Android  First, I add a assets folder to project and create a file named mytext.txt. After that, I design a layout with 1 Button in the top and 1 TextView in Bottom to show a readable text. Lastly, I read

try this:

public String getAssetsPdfPath(Context context) {
String filePath = context.getFilesDir() + File.separator + "myFile.pdf";
File destinationFile = new File(filePath);

try {
FileOutputStream outputStream = new FileOutputStream(destinationFile);
InputStream inputStream = context.getAssets().open("myFile.pdf");
byte[] buffer = new byte[1024];
int length = 0;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
Log.e(context.getClass().getSimpleName(), "Error.");
}

return destinationFile.getPath();
}

How to open a PDF file saved in my assets folder of my Android app , For simiplicity download any PDF reader app from Google play store/App store Then you may open all the PDF file. Hope it will work Thanks. AssetManager class can be used to read files from asset folder in android. Through this class we can easily access any files lying inside the Assets directory of android application.

View pdf file from asset folder in android studio (Pdf , Android app from a PDF contained in the asset/raw folder within your a headache reading all those confusing StackOverflow answers. Note: PdfRenderer displays one page of the document at a time in an imageview. If your question is simply how to read a file from asset then the answer is above. UPDATE : To open a file specifying the type simply add the type in the InputStreamReader call as follow.

Display PDF in assets folder (inside APK), r/androiddev: News for Android developers with the who, what, where when and how of the Android community. Probably mostly the how. Here, you'll … Create an assets folder. Create an assets folder in your project's root folder. In Android Studio you can right click the Project outline and go to New > Directory. You can create another subfolder for text files in assets if you like. But if you do, you have to include the relative path in pubspec.yaml. See below. Add your text file to the new folder

PDF Rendering in Android App, And go through example for the rest of the procedure. In the example, you can find code for fetching files name and displaying it, reading text file, open image file and creating drawable from it and displaying the same in ImageView.

Comments
  • have You checked if the copied pdf really exists on your sd card? By the way, You should specify with Environment.getExternalStorageDirectory() to specify the path instead of "/sdcard/"
  • The pdf exists in my assets folder which will b shipped along with the app
  • So we have to must write in external storage? without copy is it possible to open directly?
  • @sunil hi I am trying the same code but getting error Activity not found.COuld you help me why is it happening
  • @poojagupta Actvity not found that you have not mentioned in the Menifest file, Check manifest file
  • @sunil I have mentioned it but still getting error for the Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType( Uri.parse("file://" + getFilesDir() + "/abc.pdf"), "application/pdf"); startActivity(intent);
  • Does this still work, after Google's latest tightening up of security on sdcards?
  • @ViddyutKhanvilkar it just didn't load anything, but would be some mistake of mine. I'm using another approach for pdf now
  • @Felipe Santiago. What approach did you take?
  • Can I use this approach for an online pdf in the server?
  • @DavidKariuki if I remeber, i did something like this stackoverflow.com/a/14578661/4407308
  • Thank you! Felipe.
  • Not a particularly constructive comment dear @RunLoop. I use this in production so I know that it works in my setup. If you care to elaborate on how it does not work for you, then maybe I would take the time to help you out.