在安卓平台上如何正确地将字符串解码为PDF?

4

我正在尝试创建一个应用程序,将一些PDF文件以Base64编码字符串的形式存储在数据库中,然后稍后解码并显示它们(使用Intent打开其他PDF阅读器)。

但是有些东西无法正常工作。我知道字节数组在存储为编码字符串之前和之后是相同的,所以不是这个问题。

我认为问题可能出在创建要用Intent打开的文件的过程中,但我不确定。

创建字符串:

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

PDF是我从这里获取的文件:

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

从字符串中获取文件:

 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;

这段代码没有任何错误,但PDF阅读器无法显示文件。我试过几个不同的阅读器,怀疑是生成的文件存在问题。

1个回答

0
原来我需要保存到外部存储而不是目录。
File dir = getStorageDir();

应该是

File dir = Environment.getExternalStorageDirectory();

然后它就可以工作了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接