我正在尝试将JSF页面转换并导出为PDF。我尝试了以下方式:
豆:
public void createPDF() {
try {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(new URL(url).toString());
renderer.layout();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=\"" +PDF_FILE_NAME+ "\"");
OutputStream browserStream = response.getOutputStream();
renderer.createPDF(browserStream);
} catch (Exception ex) {
Logger.getLogger(PdfBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
使用创建PDF按钮的页面/home.xhtml
:
<ui:define name="content">
<center>
<h:form id="pdfgen">
<h:panelGrid columns="2">
<h:outputText value="Enter Name:"/>
<h:inputText value="#{pdfBean.name}"/>
</h:panelGrid>
<h:commandButton value="Create PDF" action="#{pdfBean.createPDF()}"/>
</h:form>
</center>
</ui:define>
我要转换的网页:
<ui:define name="content">
<center>
<h:outputText value="Hello #{pdfBean.name}"/>
</center>
</ui:define>
当我尝试我只获得一次PDF时,再也不会。我得到了以下Facelet异常:
SEVERE: Error Rendering View[/home.xhtml]
java.lang.IllegalStateException: PWC3991: getOutputStream() has already been called for this response
...
WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
java.lang.IllegalStateException: PWC3991: getOutputStream() has already been called for this response
我做错了什么?
更新Bean:请参阅BalusC的回答:
public void createPDF() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
String servername = externalContext.getRequestServerName();
String port = String.valueOf(externalContext.getRequestServerPort());
String appname = externalContext.getRequestContextPath();
String protocol = externalContext.getRequestScheme();
this.url = protocol + "://" + servername + ":" + port + appname + PDF_PAGE;
try {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(new URL(url).toString());
renderer.layout();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=\"" + PDF_FILE_NAME + "\"");
OutputStream browserStream = response.getOutputStream();
renderer.createPDF(browserStream);
} catch (Exception ex) {
Logger.getLogger(PdfBean.class.getName()).log(Level.SEVERE, null, ex);
}
facesContext.responseComplete();
}
答案 0 :(得分:8)
你需要告诉JSF你已经掌握了响应处理,并且当action方法完成时,JSF不应该处理默认导航。将其添加到操作方法的末尾:
facesContext.responseComplete();
更新,您正在访问ExternalContext
作为实例变量,表明您已将其分配为FacesContext
作为类变量,{{1或者作为会话范围bean的属性。这绝对是一个坏主意。您应该通过static
和从不将它们作为类变量分配到本地方法中。它们被绑定到一个特定的请求线程,该线程在下一个请求中不再存在。