convert base64 string to pdf android code example

Example 1: convert base64 to pdf in android studio

import java.io.File;
import java.io.FileOutputStream;
import java.util.Base64;

class Base64DecodePdf {
  public static void main(String[] args) {
    File file = new File("./test.pdf");

    try ( FileOutputStream fos = new FileOutputStream(file); ) {
      // To be short I use a corrupted PDF string, so make sure to use a valid one if you want to preview the PDF file
      String b64 = "JVBERi0xLjUKJYCBgoMKMSAwIG9iago8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvRmlyc3QgMTQxL04gMjAvTGVuZ3==";
      byte[] decoder = Base64.getDecoder().decode(b64);

      fos.write(decoder);
      System.out.println("PDF File Saved");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Example 2: convert base64 to pdf object for pdf reader in android studio

case PDF:
    try {
        byte[] pdfAsBytes = Base64.decode(file.getContent(), Base64.DEFAULT);
        File dir = getStorageDir();
        File pdffile = new File(dir, file.getName());
        if(!pdffile.exists())
        {
            pdffile.getParentFile().mkdirs();
            pdffile.createNewFile();
        }
        Files.write(pdfAsBytes, pdffile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(Uri.fromFile(pdffile), "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(pdfIntent);
    } catch (IOException e) {
        e.printStackTrace();
    }

    break;

Tags:

Java Example