Thursday, January 16, 2014

How to generate PDF in Liferay PrimeFaces Portlet with iText

The objective of this post is to show how to generate PDF with iText in Liferay PrimeFaces Portlet.
The idea is to generate the PDF stream with iText and then download it with <p:fileDownload />.

Platform:
Liferay 6.1.1
PrimeFaces 3.5
iText 2.0.8 and core-renderer-R8

Steps:
1. Create the content in PDF stream with iText
    public byte[] getPdfStream() {
      byte[] pdf = null;
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      String html = "<!DOCTYPE HTML><html><body>Generate PDF Test</body></html>";
      try {
              ITextRenderer itextRenderer = new ITextRenderer();
              itextRenderer.setDocumentFromString(html);
              itextRenderer.layout();
              itextRenderer.createPDF(baos);
              pdf = baos.toByteArray();
      }
      catch (Exception e) {
       e.printStackTrace();
      }
    }


2. Prepare the StreamedContent as <p:fileDownload /> value
    public StreamedContent getPdfFile() throws Exception {
     PortletResponse portletResponse = (PortletResponse) FacesContext
      .getCurrentInstance().getExternalContext().getResponse();
     HttpServletResponse res = PortalUtil
      .getHttpServletResponse(portletResponse);
     res.setHeader("Content-Disposition", "attachment; filename=\""
          + "test-kian.pdf" + "\"");//
     res.setHeader("Content-Transfer-Encoding", "binary");
     res.setContentType("application/pdf");

  res.flushBuffer();
  OutputStream out = res.getOutputStream();
  out.write(getPdfStream());

     return null;
    }


3. Download the PDF with <p:fileDownload /> in xhtml
<p:commandButton value="download PDF" ajax="false">
    <p:fileDownload value="#{myBean.pdfFile}" />
</p:commandButton>

4. To generate styled PDF, please refer How to generate styled PDF in Liferay PrimeFaces Portlet with iText


Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...