Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create pdf from binary data in java

Tags:

java

pdf

java-io

I'm getting this string from a web service.

"JVBERi0xLjQKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL1Jlc291cmNlcyAyIDAgUgovR3JvdXAgPDwvVHlwZSAvR3JvdXAgL1MgL1RyYW5zcGFyZW5jeSAvQ1MgL0RldmljZVJHQj4"

It is supposed to be a pdf file, i tried this library pdfbox from apache, but it writes the content as a text inside the pdf. I've tried with ByteArrayInputStream but the pdf created is not valid, corrupted, this is some of the code i've wrote.

public void escribePdf(String texto, String rutaSalida) throws IOException{

    byte[] biteToRead = texto.getBytes();
    InputStream is = new ByteArrayInputStream(biteToRead );
    DataOutputStream out = new DataOutputStream(new  BufferedOutputStream(new FileOutputStream(new File(rutaSalida))));
    int c;
    while((c = is.read()) != -1) {
        out.writeByte(c);
    }
    out.close();
    is.close();

}
like image 922
OJVM Avatar asked Feb 12 '23 22:02

OJVM


2 Answers

That is Base64 encoded (most probably UTF-8) data, you must decode it before using; such as:

import sun.misc.BASE64Decoder;

...

BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(biteToRead);

....

Edit: For java >= 1.8, use:

byte[] decodedBytes = java.util.Base64.getDecoder().decode(biteToRead);
like image 139
user3648895 Avatar answered Feb 15 '23 12:02

user3648895


[JDK 8]

Imports:

import java.io.*;
import java.util.Base64;

Code:

// Get bytes, most important part
byte[] bytes = Base64.getDecoder().decode("JVBERi0xLjQKMyAwIG9iago8P...");
// Write to file
DataOutputStream os = new DataOutputStream(new FileOutputStream("output.pdf"));
os.write(bytes);
os.close();
like image 29
Patricio Córdova Avatar answered Feb 15 '23 14:02

Patricio Córdova