Monday 18 June 2012

Node.js to ColdFusion - REST api


In my earlier post I explained how to expose a pdf service using ColdFusion REST api here.
In that post we saw that from the client side if I will pass a html document to this service it will convert it into pdf document and will return it back to the client. Also in my earlier post I gave an example to consume it using CF client itself. But there are times when your client side may not be ColdFusion. For that purpose I am giving an example to consume it using Node.js

Node.js server will act as a client over here and will contact ColdFusion to convert a document into pdf document.

Let's take a look at the code.

Sunday 17 June 2012

ColdFusion html to pdf service - rest api


Convert a html document to PDF using ColdFusion <cfdocument> and REST power.

If you are not sure about how to start with REST, you can read my blogs here.

So let's write a CFC which will be exposed as pdf service using REST api.


Explanation:
Over here we have exposed a ColdFusion component as a REST resource - pdf, which will accept an html body and will return a pdf file in binary.

In the only function present, I am accepting POST request and will produce the content in "application/xml" format. POST request will be accepted because my httpmethod attribute in the function is POST and produces attribute is "application/xml" so it will produce xml content.

There is a point to note that even though I am producing xml content but still the produced string will not contain any xml tags. That is because ColdFusion only serializes the return variable in xml/json if it is complex variable like an Array, a Struct, a CFC etc.. As we are producing a binary which is a simple data type, so it will not be serialized rather will be returned as it is.

For consuming the data I am looking for argument in body of the request. Generally you will find the restargsource attribute present in <cfargument> tag to tell you where to look for the data. But if it's absent ColdFusion looks for the argument in the body of request.

Inside the function I am using <cfdocument> tag to convert the HTML body passed from client into PDF file. This PDF file will be saved in a variable name "pdffile" in binary format. And then returning this pdffile as it is in binary format back to the client.

Client side can be written in any language but here I will write an exmaple in ColdFusion itself.

All we need to do in client side is to call this service with POST http request and pass the HTML content in the body of the request.
..
In this example I am reading a html file from local directory and passing it's content to the service we just exposed.
And finally we are saving the result we have got back to sample.pdf

That's it. We are done.