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