Android - String in Base64 Decode for pdf

Asked

Viewed 902 times

0

Hello,

The goal is to Decode a Base64 string and move it to PDF format and open (no need to download to android device).

Right now I have this:

public void onClick(View view) {
        int position = getAdapterPosition();
        //Toast.makeText(ctx, "Sapo" + position + base64Strisng, Toast.LENGTH_SHORT).show();
        Log.e("Test", base64String.toString());
        try {


            //Não sei como fazer o decode da string e passar para o itent

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(f), "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            ctx.startActivity(intent);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Update 1

@Override
    public void onClick(View view) {
        int position = getAdapterPosition();
        //Toast.makeText(ctx, "Sapo" + position + base64Strisng, Toast.LENGTH_SHORT).show();
        Log.e("Test", base64String.toString());

        byte[] pdfStream = Base64.decode(base64String, 0);
        InputStream inputStream = new ByteArrayInputStream(pdfStream);
        File file ;
        try {

            file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "sapo.pdf");
            Logger.getLogger("createFile: "+file.getAbsolutePath());
            OutputStream outputStream = new FileOutputStream(file);
            IOUtils.copy(inputStream, outputStream);
            outputStream.close();


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

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Update 3

Problem solved, I was doing Code wrong

What I had (wrong):

byte[] pdfStream = base64String.getBytes(Standardcharsets.UTF_8);

What I have changed (correct)

byte[] pdfStream = Base64.Decode(base64String, 0);

1 answer

0

If your goal is to use the file only as temporary, you can use the function createTempFile, as shown in the example below:

public File getTempFile(Context context, String url) {
File file;
try {
    String fileName = Uri.parse(url).getLastPathSegment();
    file = File.createTempFile(fileName, null, context.getCacheDir());
} catch (IOException e) {
    // Error while creating file
}
    return file;
}

On the website of android Developers has more examples

  • I updated my post because I made changes.

Browser other questions tagged

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