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

Convert PDF to Base64 in Java

To encode a PDF file to Base64 you have to read all file bytes and encode them to Base64 using the Base64.Encoder class. Please keep in mind, that the example below prints the Base64 string to console, so use only small PDF files for tests or write the output into a text file.

import java.io.File;
import java.nio.file.Files;
import java.util.Base64;

class Base64EncodePdf {
  public static void main(String[] args) {
    try {
      File file = new File("./test.pdf");
      byte [] bytes = Files.readAllBytes(file.toPath());

      String b64 = Base64.getEncoder().encodeToString(bytes);
      System.out.println(b64); //-> "JVBERi..."
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
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.