Wednesday, March 2, 2011

How-to launch browser print dialog when showing printable page


allows developers to show a print version of the current ADF Faces page to users.
However, still users will have to actively launch the browser print dialog to print the page. This OTN harvest entry shows you how to automatically open the print dialog from a page phase listener.
Note: While the following solution does the trick, it is using an internal request parameter to identify the printable page state. In general it is not recommended to work with ADF Faces internal APIs, as they may change in the future. For this reason, I filed an enhancement request (ER 11687447) for this or a similar parameter to be exposed as public.
The solution outlined in this harvest note uses a page phase listener defined on the f:view tag of the document holding the printable area.
<f:view beforePhase="#{BrowseDepartmentsBean.beforePhaseMethod}">
  ...
</f:view>
The beforePhase property points to a managed bean method, which you create declaratively using Oracle JDeveloper.  To create the managed bean and the method therein, open the Property Inspector for the f:view tag and press the arrow icon next to the beforePhase property. Choose Edit from the context menu and provide the required information in the opened dialog.
In the managed bean method, you need to listen for the RENDER_RESPONSE phase, which is the right time to add a little JavaScript required for launching the browser print dialog. The before phase listener code is shown here:
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;
...
public void beforePhaseMethod(PhaseEvent phaseEvent) {
  //only perform action if RENDER_RESPONSE phase is reached
  if (phaseEvent.getPhaseId() == PhaseId.RENDER_RESPONSE){
    FacesContext fctx = FacesContext.getCurrentInstance();
    //check internal request parameter
    Map requestMap = fctx.getExternalContext().getRequestMap();
    Object showPrintableBehavior =                   
 requestMap.get("oracle.adfinternal.view.faces.el.PrintablePage");            
    if(showPrintableBehavior != null){
      if (Boolean.TRUE == showPrintableBehavior){
         ExtendedRenderKitService erks = null;
         erks = Service.getRenderKitService(
                           fctx,ExtendedRenderKitService.class);
         //invoke JavaScript from the server
         erks.addScript(fctx, "window.print();");
      }
    }            
  }
}
When the printable page renders, the code above is invoked before the RENDER_RESPONSE phase to check for the oracle.adfinternal.view.faces.el.PrintablePage request parameter. If the parameter is set, and if its value is set to true then the window.print() command is executed on the client using the Apache Trinidad ExtendedRenderKitService class.

No comments:

Post a Comment