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);
}
}
要保存整個PDF共享偏好的內容?你確定嗎?該文檔說:''如果您想要保存的鍵值的集合相對較小,則應該使用SharedPreferences API。「您的pdf不是很小,是嗎? – pskink
pdf將僅爲1/2頁,並將檢查最大內存。我已將base64圖像數據存儲到sharedPreference,並且運行良好。這可能是共享首選項的內存問題嗎? –
共享首頁是不是爲這樣的事情設計的,更多的存儲選項在這裏:https://developer.android.com/guide/topics/data/data-storage.html – pskink