title: JSF2.0 open a pdf file of XHTML view using command button
body: <p>I tried to export current jsf page to pdf. Code as follows:</p>
  
  <p>Page with command button <code>index.html</code></p>
  
  <pre><code>&lt;?xml version='1.0' encoding='UTF-8' ?&gt;
   &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"&gt;
     &lt;h:head&gt;
      &lt;title&gt;Facelet Title&lt;/title&gt;
    &lt;/h:head&gt;
    &lt;h:body&gt;
      &lt;h:form&gt;
          &lt;h:inputText value="#{bean.name}" id="name" &gt;&lt;/h:inputText&gt;
          &lt;h:commandButton value="click" id="btn" actionListener="#{bean.writePDF}"&gt;&lt;/h:commandButton&gt;
      &lt;/h:form&gt;
  &lt;/h:body&gt;&lt;/html&gt;
  </code></pre>
  
  <p><code>writePDF()</code> function for action button is as follows:</p>
  
  <pre><code>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();
   }
  </code></pre>
  
  <p>On click of command button only a blank pdf page is generating with no control and value in it.
  Am I doing something wrong, kindly suggest.</p>
  
  <p>Thanks in advance.</p>