I am attempting to print a HTML page which I have generated using Node.js at my server. I have brought the page to client side as a response to an AJAX request and have it in a javascript variable.
var resp_json = printRequest.getResponseJson();
Now I am trying to print the rendered HTML page (i.e. without the tags) not the DOM object that would be sent.
I read about window.print() but it only prints the current page in the browser. Can anyone suggest me a way to approach.
Also, is generating an HTML page at the node is the right approach or should be it any other kind of document. The page is supposed to be dynamically generated at the node and the end result should be a printed document. Thanx in advance!!
P.S. I am using closure library, don't ask why, that was already decided for me.
P.P.S. I am fairly new to javascript and node.js so don't be afraid to give lengthy lectures, I am all ears!!
Without pop-up
function printHTMLString(htmlString) {
var originalDocument = document.body.innerHTML;
document.body.innerHTML = htmlString;
window.print();
document.body.innerHTML = originalDocument;
}
With pop-up
var popupWIndow = window.open('','','width=200,height=100');
popupWIndow.document.write(jsonResponse);
popupWindow.window.print();
if for some reason it doesn't work, add following line before print()
popupWindow.window.location.reload();
Also you need to convert json object to string before printing
JSON.stringify(jsonObject)
but for all of this to work, browser has to be able to read it as an HTML page so it can render it. JSON objects won't work.
You could use https://code.google.com/p/wkhtmltopdf/
With it you can render a pdf from whatever page wether directly from url or by file. It will render the page as pdf you could then print the entire pdf.
nb : you can print one page or concatenate multiple pages.
Common practice is to open a new browser window with the content you want to print, then invoke window.print()
you can create an iframe, add your html page to iframe.src and then call print:
window.frames[yourIframeName].focus();
window.frames[yourIframeName].print();