2017-06-13 272 views
0

我想先選擇pdf文件,然後將其編碼爲base64並將其保存爲共享首選項。之後,解碼並保存爲pdf。並打開該pdf查看。Android:將pdf編碼爲base64並解碼爲pdf給出「此文檔無法打開」

打開時顯示消息「本文檔無法打開」。看起來編碼/解碼部分存在一些問題。我不知道在哪裏。所以,如果有人有想法,這對我來說會很有幫助。謝謝,

我的代碼如下:

編碼:

public static String getBase64Pdf(String pdfFilePath){ 
    try{ 
     InputStream inputStream = new FileInputStream(pdfFilePath); 
     byte[] byteArray = IOUtils.toByteArray(inputStream); 
     String encodedPdfString = Base64.encodeToString(byteArray, Base64.DEFAULT); 
     PrintLog.showTag(TAG,"pdf converted to string : " + encodedPdfString); 
     return encodedPdfString; 
    }catch (IOException e){ 
    } 
    return ""; 
} 

解碼,保存到文件並打開PDF:

private void openPdfViewer(){ 
    try{ 
     PrintLog.showTag(TAG,"== opnPdfViewer & length of base64 string is ==" 
       + sessionManager.getBase64ProofImage().length()); 

     //== decode and write file here 
     String base64pdf = sessionManager.getBase64ProofImage();//gets base64 from shared preference 
     final File newFilePath = new File(getActivity().getFilesDir(), "warrantyProof.pdf"); 
     byte[] pdfAsBytes = Base64.decode(base64pdf, Base64.NO_WRAP); 
     FileOutputStream os; 
     os = new FileOutputStream(newFilePath, false); 
     os.write(pdfAsBytes); 
     os.flush(); 
     os.close(); 

     //==== open pdf file here 
     File file = new File(getActivity().getFilesDir(),"warrantyProof.pdf"); 

     Intent intent = new Intent(Intent.ACTION_VIEW); 
     intent.setDataAndType(Uri.fromFile(file), "application/pdf"); 
     intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 
     startActivity(intent); 
    }catch (IOException e){ 
     PrintLog.showException(TAG,"IO exception saving pdf ",e); 
    } 
    catch (Exception e){ 
     PrintLog.showException(TAG,"exception opening pdf",e); 
    } 
} 
+0

要保存整個PDF共享偏好的內容?你確定嗎?該文檔說:''如果您想要保存的鍵值的集合相對較小,則應該使用SharedPreferences API。「您的pdf不是很小,是嗎? – pskink

+0

pdf將僅爲1/2頁,並將檢查最大內存。我已將base64圖像數據存儲到sharedPreference,並且運行良好。這可能是共享首選項的內存問題嗎? –

+1

共享首頁是不是爲這樣的事情設計的,更多的存儲選項在這裏:https://developer.android.com/guide/topics/data/data-storage.html – pskink

回答

0
File dir = Environment.getExternalStorageDirectory(); 
    File yourFile = new File(dir, "path/to/the/file/inside/the/myfile.ext"); 
    String encodeFileToBase64Binary = encodeFileToBase64Binary(yourFile); 

    private static String encodeFileToBase64Binary(File fileName) throws IOException { 
      byte[] bytes = loadFile(fileName); 
      byte[] encoded = Base64.encodeBase64(bytes); 
      String encodedString = new String(encoded); 
      return encodedString; 
    } 
+0

您能否解釋一下,解決這個錯誤的方法,還是您提供了一段正確的代碼?謝謝。 –