Hello,
I would like to display a document (for example PDF) as a result of
an action in a separate browser window. This is a typical situation:
The user enters some data in a form, presses a print button and a generated
report is displayed in a new browser window, where he or she can print it.
I tried two approaches: The first works only partly, the second works good, but
both seems to me a little bit ugly. I think, there must be a prettier way to do
this.
Regards
Helmut
First approach
--------------
JSP
...
<tc:script>
function printAction() {
// Redirect result from action to a new window
document.forms[0].target = "Print";
Tobago.submitAction('page:printButton');
document.forms[0].target = "";
}
</tc:script>
...
<tc:button label="Print" id="printButton"
onclick="javascript:printAction()"
action="#{printController.printAction}"/>
...
PrintController
public void printAction() {
// Generate PDF file
...
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
try {
// Return PDF file as result
ec.redirect("http://localhost:8080/gena/print/test.pdf");
} catch (IOException e) {
LOG.error("printAction", e);
}
}
The Problem with this solution is, that every second time the print button
is pressed, the page itself is redisplayed in the new window and not the
PDF file. I can't tell you why.
Second approach
---------------
JSP
...
<tc:script onload="showPrintResult('#{printController.printFile}')">
// Everytime the page is loaded, check for an existing PDF file to display
function showPrintResult(url) {
if (url != null && url != "") {
window.open(url, "Print");
}
}
</tc:script>
...
<tc:button label="Print" id="printButton"
action="#{printController.printAction}"/>
...
PrintController
public void printAction() {
// Generate PDF file
...
// Set PDF file
printFile = "http://localhost:8080/gena/print/test.pdf";
}
public String getPrintFile() {
// Return and reset PDF file
String tmp = printFile;
printFile = null;
return tmp;
}