How to open a PDF file, which is in the Assets of my APP, in a PDF reader already installed on mobile phone?

Asked

Viewed 476 times

2

I have an APP that needs to open some PDF files (laws) that should come along with the application.

The idea is to call a Intent to open these PDF files by the PDF reader itself already installed on the mobile. The files are in the Assets. How do I intend to open the PDF with the file path that is on Assets?

Here on the site was passed me, as an example, the following link:
https://gist.github.com/alhazmy13/c93c5e083ec0b7fe6d1c

Through the above example I did what follows below in MainActivity.java:

package com.vdtecnologia.br.pdfassets;

import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {



    Button btn1;
    private String TAG;

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

        btn1 = (Button) findViewById(R.id.button);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                openPDFFiles("AnexoI.pdf");


            }
        });



    }



    private void openPDFFiles(String AnexoI) //fileName is the pdf file name which is keep in assets folder. ex file.pdf
    {
        AssetManager assetManager = getAssets();

        InputStream in = null;
        OutputStream out = null;
        File file = new File(getFilesDir(), "");
        try {
            in = assetManager.open(AnexoI);
            out = openFileOutput(file.getName(), MODE_PRIVATE);

            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("file://" + getFilesDir() + "/"+AnexoI), "application/pdf");
            startActivity(intent);
        }catch (RuntimeException ex){
            Toast.makeText(MainActivity.this, "Não foi encontrado nenhum leitor de PDF no seu dispositivo", Toast.LENGTH_SHORT).show();
        }

    }

    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);
        }
    }
}

But by clicking the button it triggers the PDF reader and then back to the APP with the following message:

Could not access file. Check location or network and try again.

1 answer

-1

Switch your PDF level from Assets to raw and try this.

protected void openPDF() {

        if(Build.VERSION.SDK_INT>=24){
            try{
                Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
                m.invoke(null);
            }catch(Exception e){
                e.printStackTrace();
            }
        }

        File dest = Environment.getExternalStorageDirectory();
        InputStream in = getResources().openRawResource("CAMINHO DO SEU ASSETS(RAW)");

        try
        {
            OutputStream out = new FileOutputStream(new File(dest, "NOME_DO_ARQUIVO.pdf"));
            byte[] buf = new byte[1024];
            int len;
            while ( (len = in.read(buf, 0, buf.length)) != -1)
            {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }
        catch (Exception e) {}

        Intent share = new Intent();
        share.setAction(Intent.ACTION_VIEW);
        share.setType("application/pdf");
        File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "NOME_DO_AQUIVO.pdf");
        Uri uri = Uri.fromFile(path);
        share.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(share);
    }
  • Good evening! How do I change the pdf level from Assets to raw?

  • I created the raw folder. It happens that this giving error in the encoding where you had put "THE PATH OF YOUR ASSETS (RAW)".

  • On the line it looks like this: File dest = Environment.getExternalStorageDirectory(); Inputstream in = getResources(). openRawResource(Integer.parseint("res/raw"));

  • But the APP doesn’t work. It simply closes with the message that the app stopped. I don’t know if the path to the raw folder (which is inside the res folder) is correct.

  • put R.raw.filename pdf

  • I did what you said, but it didn’t work. The app keeps closing with the message that the app stopped.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.