How to Convert Pdf to base64 and Encode / Decode

DKKs picture DKKs · Aug 29, 2018 · Viewed 50.4k times · Source

OK, I have some pdf need convert to base64 by base64encoder.

finally, I use decoder to convert back to pdf format but my content is lost.

my code :

byte[] input_file = Files.readAllBytes(Paths.get("C:\\user\\Desktop\\dir1\\dir2\\test3.pdf"));
    byte[] encodedBytes = Base64.getEncoder().encode(input_file);

    String pdfInBase64 = new String(encodedBytes);
    String originalString = new String(Base64.getDecoder().decode(encodedBytes));

    System.out.println("originalString : " + originalString);

    FileOutputStream fos = new FileOutputStream("C:\\user\\Desktop\\dir1\\dir2\\newtest3.pdf");
    fos.write(originalString.getBytes());
    fos.flush();
    fos.close();

result :

Encode : https://pastebin.com/fnMACZzH

Before base64encode

After decode

Thank You

Answer

Ajit Soman picture Ajit Soman · Aug 29, 2018

You can decode base64 encoded String and pass that byte[] to FileOutputStream write method to fix this issue.

        String filePath = "C:\\Users\\xyz\\Desktop\\";
        String originalFileName = "96172560100_copy2.pdf";
        String newFileName = "test.pdf";

        byte[] input_file = Files.readAllBytes(Paths.get(filePath+originalFileName));

        byte[] encodedBytes = Base64.getEncoder().encode(input_file);
        String encodedString =  new String(encodedBytes);
        byte[] decodedBytes = Base64.getDecoder().decode(encodedString.getBytes());

        FileOutputStream fos = new FileOutputStream(filePath+newFileName);
        fos.write(decodedBytes);
        fos.flush();
        fos.close();