【问题标题】:How to show PDF from Base64 String on Android?如何在 Android 上显示来自 Base64 字符串的 PDF?
【发布时间】:2019-10-30 21:53:40
【问题描述】:

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

【问题讨论】:

    标签: android pdf base64 blob


    【解决方案1】:

    由于您拥有 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"/>
    

    【讨论】:

    • Uri 路径 = Uri.fromFile(file);文件应该在哪里?
    • 我收到一个错误。 file:///myPdf.pdf 通过 Intent.getData() 暴露在应用程序之外
    • 如果未添加则添加写入外部存储权限
    • 我还没试过。尝试后我会写评论。
    猜你喜欢
    • 2022-07-26
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    相关资源
    最近更新 更多