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) {
Comments (2)

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

  • GanesanM,
    Good website
  • Ram,
    Very Nice and Clean
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.