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.