How to decode PDF from String on Android correctly?

I am trying to create an application that will store some PDf files as base64 encoded strings in a database, and then decode and send them later (with the intention of opening another PDF reader). But something is not working properly. I know that the byte array remains the same before and after storage as an encoded string, so this is not a problem. I think the problem is that the file creation process is opened with the intention, but I'm not sure.

Line Creation:

 byte[] b = Files.toByteArray(pdf);
 String encodedFile = Base64.encodeToString(b, Base64.DEFAULT);

pdf is the file I get from this:

else if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
    {
        Uri uri = data.getData();
        try {
            String fileName = uri.toString();
            fileName = fileName.substring(fileName.length()-10);
            service.addPDF(order, fileName, new File(uri.getPath()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        updateFileList();
    }

Getting a file from a string:

 case PDF:
    try {
        byte[] pdfAsBytes = Base64.decode(file.getContent(), Base64.DEFAULT);
        File dir = getStorageDir();
        File pdffile = new File(dir, file.getName());
        if(!pdffile.exists())
        {
            pdffile.getParentFile().mkdirs();
            pdffile.createNewFile();
        }
        Files.write(pdfAsBytes, pdffile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(Uri.fromFile(pdffile), "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(pdfIntent);
    } catch (IOException e) {
        e.printStackTrace();
    }

    break;

This code works without errors, but the PDF viewer cannot display the file. I tried with several viewers. I suspect the resulting file

+4
1

, .

File dir = getStorageDir();

File dir = Environment.getExternalStorageDirectory();

.

0

Source: https://habr.com/ru/post/1598851/


All Articles