我想首先选择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);
}
}
答案 0 :(得分: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;
}