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
Sometimes you have to send or output a PDF file within a text document (for example, HTML, JSON, XML), but you cannot do this because binary characters will damage the syntax of the text document. To prevent this, for example, you can encode PDF file to Base64 and embed it using the data URI.
To decode a file with contents that are base64 encoded, you simply provide the path of the file with the --decode flag. As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.
Convert Files to Base64Just select your file or drag & drop it below, press the Convert to Base64 button, and you'll get a base64 string. Press a button – get base64. No ads, nonsense, or garbage. The input file can also be an mp3 or mp4.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With