Thursday, October 29, 2009

Implementing Print functionality for a web content

This is almost straight forward implementation just follow few steps.

Step 1. Get the page url u want to print I am thinking I am on the same page

of which I wanted to print the content . Then I can get the url like this

PortletURL url = PortletURLUtil.getCurrent(renderRequest, mimeResponse or renderResponse);

else you can create the url of the page like this

PortletURL printPageURL = renderResponse.createRenderURL();

and set the required parameter related to youur page plus these extra parameters

printPageURL.setWindowState(LiferayWindowState.POP_UP);
printPageURL.setParameter("viewMode", Constants.PRINT);


sample url will look like this :
PortletURL printPageURL = renderResponse.createRenderURL();
printPageURL.setWindowState(LiferayWindowState.POP_UP);
printPageURL.setParameter("struts_action", "ur_stuts_action_path");
printPageURL.setParameter("ur_param_1", "ur_param_value_1");
printPageURL.setParameter("viewMode", Constants.PRINT);
printPageURL.setParameter("print", String.valueOf(true));

Step 2:
create a boolean variable print with default value false.
eg:
boolean print = ParamUtil.getBoolean(request,"print");

Step 3: Add this code on your page.

<c:choose>
<c:when test="<%= print %>">
<script type="text/javascript">
function printArticle() {
print();
}
</script>
</c:when>
<c:otherwise>

<script type="text/javascript">
function <portlet:namespace />printPage() {
window.open('<%= printPageURL.toString()%>', '', "directories=0,height=480,left=80,location=1,menubar=1,resizable=1,scrollbars=yes,status=0,toolbar=0,top=180,width=640");
}
</script>
</c:otherwise>
</c:choose>

Step 4: Add this code

<c:choose>
<c:when test="<%= print %>">
<span style="float:right">
<liferay-ui:icon image="Print" url="javascript:onclick=printArticle();" label="<%= false %>" />
</span>
</c:when>
<c:otherwise>
<span style="float:right">
<liferay-ui:icon image="Print" url='<%= "javascript:" + renderResponse.getNamespace() + "printPage();" %>' label="<%= false %>" />
</span>
</c:otherwise>
</c:choose>

Thats it
Enjoy !!!

2 comments:

Anonymous said...

nice one..

Anonymous said...

nice one