I have an XML response from a SOAP web service. This response has a binary PDF inside a specific tag, something like
<binaryObject>JVBERi0xLjQNCiVET0MxIFJlc2...</binaryObject>
I'd like to extract the binary part and convert it back to a PDF file. So I get the tag content parsing the XML into an org.w3c.Document and using XPath:
String binary = XMLUtils.evalXPath(doc, "//binaryObject//text()");
Which works fine, then tried something like this:
byte[] buffer = new byte[8 * 1024];
// get the binary string as an array of bytes
InputStream input = new ByteArrayInputStream(binary.getBytes("Cp1252"));
int totalBytes = 0;
try {
OutputStream output = new FileOutputStream(PATHDOWNLOAD + File.separator + fileName);
try {
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
totalBytes += bytesRead;
}
} finally {
output.close();
}
} finally {
input.close();
logger.info("Done. " + totalBytes + " bytes written.");
}
It writes down the file but well, it's unreadable as a PDF. Tried different kinds of encoding, still getting a simple text file and no more. Probably something lost in translation from file to text to file again, but I can't imagine a way to make it work. I'm forced to get the response in String format 'cause I need to get the right tag, but then I can't decode the binary part. Any ideas?
ADDENDUM. If I try to log to console the binary content (when it's still String) it clears the screen and prints out the last part from different points depending on the execution. Don't know if it can help.