I am trying to first select pdf file, then encode it to base64 and save it to shared preference. After that, decode and save to pdf. And open that pdf to view.
When opening it displays message "This document cannot be opened". It looks like there was some problem on encoding/decoding part. I don't know where. So, if anyone has idea on it, It would be great help for me. Thanks,
My code is as follows:
Encoding :
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 "";
}
Decoding, saving to file and open 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);
}
}