A virtual teacher who reveals to you the great secrets of Base64

Convert Base64 to PDF in Java

To convert a Base64 string to PDF file in Java you have to use the Base64.Decoder class and any convenient way to write a byte array to file (it is important to note that Base64.getDecoder().decode() returns a byte array, not a string).

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();
    }
  }
}
Comments (6)

I hope you enjoy this discussion. In any case, I ask you to join it.

  • Arturo,
    I get error getDecoder (). Decode (b64) that I have to do to initialize or fix that error
    • Administrator,
      Hi! Can you please specify the full error message and your Java version?
  • Sudhik,
    Thank You. I was writing the PDF file with String from decoder and it would show blank pages. When I write as byte[] it shows the content.
  • Dipak,
    Hello! Thanks for the code snippet. When I run the program, it created a PDF file but when I try open the file, it say "There was an error opening the file. The file is damaged and could not be opened". Please help!
    • Administrator,
      Hello,
      To be short, the code snippet contains only first bytes of a PDF file, but as I pointed out in the example, you should specify a valid Base64 string (for example, use this one).
  • Praveen,
    Hi,

    What if my encoded string size is more than 65535. Will it work?
Add new comment

If you have any questions, remarks, need help, or just like this page, please feel free to let me know by leaving a comment using the form bellow.
I will be happy to read every comment and, if necessary, I will do my best to respond as quickly as possible. Of course, spammers are welcome only as readers.

Loading...