Writing Binary Data from a Notes Agent
Writing Binary Data from a Notes Agent:
When working with Notes Web Agents, you would come across scenarios where you would have to send Binary Data back to the browser.
Unfortunately Agent Base class provided by Domino doesn’t have any suitable Method that we can invoke.
There is an undocumented Method called “getAgentOutputStream”, which would return the OutPutStream instance of the agent, but this method is broken and would perform partial writes, corrupting the file we like to send to the browser.
Many share my frustration with it.
We can use Printwriter instance provided by “getAgentOutput” method, but this wouldn’t do much good, since Printwriter can be used to write only character data.
Hence most used solution is to simply create a Notes Document with the binary file as attachment and send the link to the browser. While this solution would work in most cases, I didn’t find this suitable for my need.
Alternative Approach:
My approach involves two major steps.
Step 1: Convert the Byte Array as JSON Array String.
Write a loop to create a JSON Array String with the Byte Array.
byte[] pdfFile = pdf.getPDF();
ByteBuffer byteBuffer = ByteBuffer.wrap(pdfFile);
CharBuffer result = Charset.forName("UTF-8").decode(byteBuffer);
PrintWriter agentPrintWriter = getAgentOutput();
agentPrintWriter.println("Content-type:application/pdf");
agentPrintWriter.println("Content-Disposition:attachment;filename=\"Report.pdf\"\n");
StringBuilder buffer = new StringBuilder();
buffer.append("[");
for(int index=0;index<pdfFile.length;index++)
{
buffer.append(""+pdfFile[index]);
if(index<pdfFile.length-1)
buffer.append(",");
}
buffer.append("]");
agentPrintWriter.println(buffer.toString());
The above should produce a String representing a JSON array like the one below.
“[37,80,68,70,45,49,46,52,10,49,32,48,32,111,98,106,10,60,60,….,10]”
Write this string using the PrintWriter instance of the agent.
Step 2: Create a Blob with the Received Data and Open it was Attachment
The Data received on the Client side would be a JSON String.
This can be converted to a Byte Array and downloaded as an Attachment by creating Blob object from it.
//Data Received from the AJAX Request
var byteArray = new Uint8Array(JSON.parse(data));
var blob = new Blob([byteArray], {type: "application/pdf"});
var blobUrl = URL.createObjectURL(blob);
window.open(blobUrl)
I tested the solution in Google Chrome, though I am pretty sure, it would work on other browsers as well.