Convert Base64 to PDF in Java
To convert a Base64 string to PDF file in Java you have to use the Base64.Decoder class and any convenient way to write a byte array to file (it is important to note that Base64.getDecoder().decode()
returns a byte array, not a string).
import java.io.File;
import java.io.FileOutputStream;
import java.util.Base64;
class Base64DecodePdf {
public static void main(String[] args) {
File file = new File("./test.pdf");
try ( FileOutputStream fos = new FileOutputStream(file); ) {
// To be short I use a corrupted PDF string, so make sure to use a valid one if you want to preview the PDF file
String b64 = "JVBERi0xLjUKJYCBgoMKMSAwIG9iago8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvRmlyc3QgMTQxL04gMjAvTGVuZ3==";
byte[] decoder = Base64.getDecoder().decode(b64);
fos.write(decoder);
System.out.println("PDF File Saved");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Comments (32)
I hope you enjoy this discussion. In any case, I ask you to join it.
To be short, the code snippet contains only first bytes of a PDF file, but as I pointed out in the example, you should specify a valid Base64 string (for example, use this one).
What if my encoded string size is more than 65535. Will it work?
im try this code but script pass but pdf document open without content
Please read the code carefully. There is a comment explaining what's the problem.
Im using correct PDF Base64 content but unfortunately its not working manually its working fine with out issue please help us
You can embed it via Data URI.
I'm trying to print the decoder result on the web page with an out.print(), but when I see the content, some characters change.
How do I solve that problem?
I have an encrypted binary file has been base64 encoded. I want to decode it. How can I do that?
<img src="data:documents/jpg;base64, ${doc}" alt="${ name }">
to display files from database. Can you make suggestions?I hardcoded the strings you provided in your tutorial. The red dot displays without any problems. The pdf string does not :(
Exemple: h��.�5Ĉi�I�r�\#-߸��D3H��l��uz�(q��g&���DԠ��yg��ȨA����.