Wednesday, July 1, 2009

How to return PDF file byte array from webservice

Below is the solution code snippet which shows how to pass and return pdf file byte[] as string from and to Webservice.

For the webservice as input parameter or as return parameter as String[] one needs to convert byte[] of PDF file buffer to String.

So it could be like


public String[] getDocument(String pdffileName) {
File file =null;
InputStream is = null;
String[] retParam = new String[2];
try {
file = new File(pdffileName);
is = new FileInputStream(file);

// Get the size of the file
long length = file.length();
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];

// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}

// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
String pdfByteArrayStr = new sun.misc.BASE64Encoder().encode(bytes);
retParam[0] = file.getName();
retParam[1] = pdfByteArrayStr;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if (is !=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return retParam;
}



Now Read The Parameters From WebService

String []responseParam = this.locator.getDocumentService().getDocument(pdffileName);
requestParam could be file name or any other parameter

String fileName = responseParam[0];
byte [] formBuffer = new sun.misc.BASE64Decoder().decodeBuffer(responseParam[1]);

This formBuffer can be used to either pass to FileOututStream to store file on FileSystem or to ServletOutputStream to show in browser.