我试图将当前的 jsf 页面导出为 pdf。代码如下:
带有命令按钮的页面index.html
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<h:inputText value="#{bean.name}" id="name" ></h:inputText>
<h:commandButton value="click" id="btn" actionListener="#{bean.writePDF}"></h:commandButton>
</h:form>
</h:body></html>
writePDF()
动作按钮的功能如下:
public void writePDF() {
String PDF_FILE_NAME = "converted.pdf";
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext =facesContext.getExternalContext();
HttpServletRequest request = (HttpServletRequest)externalContext.getRequest();
HttpSession session = (HttpSession) externalContext.getSession(true);
String url = request.getRequestURL().append(";jsessionid=").append(session.getId().toString()).toString();
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 + "\"");
ServletOutputStream browserStream = response.getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
renderer.createPDF(browserStream);
renderer.finishPDF();
facesContext.responseComplete();
}
catch (Exception ex)
{
ex.printStackTrace();
}
facesContext.responseComplete();
}
单击命令按钮时,只会生成一个空白的 pdf 页面,其中没有任何控件和值。我做错了什么,请建议。
提前致谢。