0 Replies Latest reply on Jul 12, 2010 7:56 PM by shavo26

    How to save pdf and serve to browser

    shavo26

      Guys,


      Here is my sample code, first for rendering pdf and persisting to database as byte array, and secondly serving file to browser.



       /**
           * Create the pdf by rendering pdf template and returning as byte array
           * @return
           */
          private byte[] createPDF() {
              byte[] bytes = null;
              try {
                      renderer.render("/generalInquiryPdf.xhtml");
                      DocumentStore doc = DocumentStore.instance();
                      if (doc != null) {
                              DocumentData data = doc.getDocumentData("1");
                              ByteArrayDocumentData byteData = null;
                              if (data instanceof ByteArrayDocumentData) {
                                      byteData = (ByteArrayDocumentData) data;
                              } else {
                                      throw new Exception("Couldnt get the bytes from the pdf document, unknown class " + data.getClass().getName());
                              }
                              bytes = byteData.getData();
                      }
              } catch (Exception ex) {
                      log.error("Error when trying to get the content of the pdf in bytes with the message #0", ex.getMessage());
                      ex.printStackTrace();
              } finally {
              }
              return bytes;
          }




      
            /**
           * Serve file to the browser
           */
          public void sendFile(byte[] file, String contentType, String filename) throws IOException {
              if (file == null) {
                  return;
              }
              FacesContext fc = FacesContext.getCurrentInstance();
              HttpServletResponse servletResponse = (HttpServletResponse) fc.getExternalContext().getResponse();
              if (filename != null) {
                  servletResponse.setHeader("Content-disposition", "attachment; filename=" + filename);
              }
              if (contentType != null) {
                  servletResponse.setContentType(contentType);
              }
              ServletOutputStream os = servletResponse.getOutputStream();
              os.write(file);
              fc.responseComplete();
          }
           
           <h:commandLink id="view" value="View"
           action="#{<ComponentName>.sendFile}" />