如何在Android上从Base64 String显示PDF?

时间:2019-06-17 10:04:27

标签: android pdf base64 blob

我正在开发一个Android应用程序。我将PDF数据作为blob类型保存在MYSQL数据库中。我正在将base64发送到Android应用。如何在Android应用中显示pdf?

1 个答案:

答案 0 :(得分:0)

当您拥有yourBase64String时,可以将其转换为字节数组,然后将其保存为文件。

   FileOutputStream fos = null;
    try {
        if (yourBase64String != null) {
           fos = context.openFileOutput("myPdf.pdf", Context.MODE_PRIVATE);
           byte[] decodedString = android.util.Base64.decode(yourBase64String , android.util.Base64.DEFAULT);
           fos.write(decodedString);                        
           fos.flush();
           fos.close();             
        }

    } catch (Exception e) {

    } finally {
        if (fos != null) {
            fos = null;
        }
    }

现在打开此PDF文件

 Uri path = Uri.fromFile(new File(myPdf.pdf));
 Intent intent = new Intent(Intent.ACTION_VIEW);
 intent.setDataAndType(path, "application/pdf");
 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

 try {
    startActivity(intent);
  } 
 catch (ActivityNotFoundException e) {
   Toast.makeText(OpenPdf.this, 
   "No Application Available to View PDF", 
   Toast.LENGTH_SHORT).show();
 }

在您的清单中添加此权限

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