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

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

  • GanesanM,
    Good website
  • Ram,
    Very Nice and Clean
  • nqhXncMU,
    (select(0)from(select(sleep(15)))v)/*'+(select(0)from(select(sleep(15)))v)+'"+(select(0)from(select(sleep(15)))v)+"*/
  • nqhXncMU,
    -1 OR 2+568-568-1=0+0+0+1 --
  • nqhXncMU,
    -1)) OR 511=(SELECT 511 FROM PG_SLEEP(15))--
  • gBqsPxAZ,
    -1)) OR 251=(SELECT 251 FROM PG_SLEEP(15))--
  • gBqsPxAZ,
    -1; waitfor delay '0:0:15' --
  • gBqsPxAZ,
    -5) OR 547=(SELECT 547 FROM PG_SLEEP(15))--
  • gBqsPxAZ,
    -1; waitfor delay '0:0:15' --
  • nqhXncMU,
    efDMVn0q') OR 746=(SELECT 746 FROM PG_SLEEP(15))--
  • nqhXncMU,
    (select(0)from(select(sleep(15)))v)/*'+(select(0)from(select(sleep(15)))v)+'"+(select(0)from(select(sleep(15)))v)+"*/
  • nqhXncMU,
    1
  • ncMUFCMU,
    -1 OR 2+80-80-1=0+0+0+1
  • nqhXncMU,
    -1); waitfor delay '0:0:15' --
  • ncMUFCMU,
    -5 OR 706=(SELECT 706 FROM PG_SLEEP(15))--
  • ncMUFCMU,
    (select(0)from(select(sleep(15)))v)/*'+(select(0)from(select(sleep(15)))v)+'"+(select(0)from(select(sleep(15)))v)+"*/
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.