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();

}
share|improve this question
    
That string may well be a valid pdf file in binary but you have to know what encoding it was made in. Java uses UTF-16 by default but not all encodings will be the same value. – James Sullivan May 19 '14 at 22:11
    
The pdf is created with php. – OJVM May 19 '14 at 22:13
1  
Don't use a DataOutputStream. Write directly to the BufferedOutputStream. – Stephen C May 19 '14 at 22:21
up vote 1 down vote accepted

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);
share|improve this answer
1  
It worked fine. thank you. – OJVM May 19 '14 at 22:27

Your string is definitively base 64 encoded. It translates to

%PDF-1.4
3 0 obj
<</Type /Page
/Parent 1 0 R
/Resources 2 0 R
/Group <</Type /Group /S /Transparency /CS /DeviceRG

which isnt a full pdf file by itself which leads me to belive you have something wrong with the way your reading the data from the server.

As of java 6 they added a base 64 converter outside the sun packages.

byte [] bytes = javax.xml.bind.DatatypeConverte.parseBase64Binary(texto);
new String(bytes, "UTF-8");
share|improve this answer
    
It works too, thank you. – OJVM May 20 '14 at 15:15

[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();
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.