Base64 to PDF in Java

Converting a Base64 encoded string to a PDF file in Java is a common task, especially when dealing with web services or database storage. Java provides built-in tools in the java.util.Base64 package that make this process straightforward.

Java Code Example

Below is a complete, ready-to-use Java snippet to decode a Base64 string and save it as a PDF document.

Base64ToPdf.java
import java.util.Base64;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class Base64ToPdf {
    public static void main(String[] args) {
        // Your Base64 encoded string
        String base64String = "JVBERi0xLjQKJ..." ; 

        try (OutputStream stream = new FileOutputStream("output.pdf")) {
            // Decode the Base64 string to a byte array
            byte[] data = Base64.getDecoder().decode(base64String);
            
            // Write the byte array to the PDF file
            stream.write(data);
            
            System.out.println("PDF created successfully!");
        } catch (Exception e) {
            System.err.println("Error creating PDF: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

How It Works

  1. Base64 Decoding: We use Base64.getDecoder().decode() to transform the encoded string back into its original binary form (byte array).
  2. File Streams: A FileOutputStream is used to create a new file named output.pdf.
  3. Writing Data: The stream.write(data) method writes the binary data directly to the file.
  4. Resource Management: Using try-with-resources ensures that the file stream is closed automatically, even if an error occurs.

Dependencies

This solution requires Java 8 or higher. No external libraries (like Apache Commons Codec or iText) are needed for basic Base64 decoding, as the standard library is fully capable.

Need a quick conversion?

You can always use our online tool for instant, secure conversion without writing any code.

Back to Converter