【发布时间】:2017-06-13 10:26:28
【问题描述】:
我正在尝试首先选择 pdf 文件,然后将其编码为 base64 并将其保存到共享首选项。之后,解码并保存为pdf。并打开该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 内容吗?你真的确定吗?文档说:
"If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs."你的 pdf 不是很小,是吗? -
pdf 将仅为 1/2 页,并将检查最大内存。我已将 base64 图像数据存储到 sharedPreference 并且运行良好。这可能是共享偏好的内存问题吗?
-
共享首选项不是为这样的事情而设计的,更多关于存储选项的信息在这里:developer.android.com/guide/topics/data/data-storage.html
-
好的,我会想办法将base64字符串存储到另一个介质(数据库或通过参数直接传递给服务器api)。谢谢,您对上述编码/解码部分有任何想法吗?我的意思是,如果那里有任何错误或问题。
-
你需要这个 base64 做什么?它只会将您的数据扩大 33%...
标签: android pdf encoding base64 decoding