Skip to main content

APIzation: Replication Package

[Q#32175041][A#32175072] how to convert Base64 to String in java (For pdf)

https://stackoverflow.com/q/32175041

I want to convert pdf to base64,thene again convert base64 to pdf. For this I converted my pdf to base64. And I am trying to convert Base64 to string usin java.But it gives wrong output. My source code Where encodedstr is Please help me.

Answer

https://stackoverflow.com/a/32175072

Your Base64-Byte-Array is already a PDF (it starts with the magic-number for PDF-Files %PDF), you can write the decoded Bytes directly to a File and have your PDF.

APIzation

try(OutputStream out = new FileOutputStream("filename.pdf")){
    out.write(decodedBytes );
} catch (IOException e) {
    e.printStackTrace();
}
package com.stackoverflow.api;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Human32175072 {

  public static void base64toPDF(byte[] decodedBytes, String str1) {
    try (OutputStream out = new FileOutputStream(str1)) {
      out.write(decodedBytes);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

package com.stackoverflow.api;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * how to convert Base64 to String in java (For pdf)
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/32175072">https://stackoverflow.com/a/32175072</a>
 */
public class APIzator32175072 {

  public static void convertBase64(int decodedBytes, String str1)
    throws Exception {
    try (OutputStream out = new FileOutputStream(str1)) {
      out.write(decodedBytes);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}