Wednesday, August 12, 2015

Writing A Word Exporter for Primefaces Datatable



PDF and Excel Export are default features of primefaces datatables.
We need a doc exporter.


I saw some other posts doing this . My solution was a bit different for some restrictions(which i do not remember know :) )

Below is simple logic and necessary classes and some codes to give an idea.

Extend  org.primefaces.component.export.Exporter
Change necessary methods to add final texts to your doc generator.


import com.lowagie.text.BadElementException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.rtf.RtfWriter2;

public class DocExporter extends Exporter {

   protected Document              document;

   protected RtfWriter2            writer;

   protected Table                 doctable = null;



protected void addColumnValue(UIComponent component) throws DocumentException {
      // int cellIndex = row.getLastCellNum() == -1 ? 0 : row.getLastCellNum();
      // Cell cell = row.createCell(cellIndex);
      String value = component == null ? "" : exportValue(FacesContext.getCurrentInstance(), component);

      com.lowagie.text.Cell cell = new com.lowagie.text.Cell(value);
      cell.setBorderColor(new Color(255, 0, 0));
      // cell.setHeader(true);

      doctable.addCell(cell);

      // cell.setCellValue(new HSSFRichTextString(value));
   }



***********************
At class extending LazyDataModel add a method as ExportDoc


public class TableModel<T> extends LazyDataModel<T> {


public void exportDoc(String reportName,boolean pageOnly) throws IOException {
      FacesContext context = FacesContext.getCurrentInstance();
      DocExporter exporter = new DocExporter();
      exporter.export(context, (DataTable) persistentUITable, reportName, pageOnly, false, "UTF-8", null, null);
      context.responseComplete();
   }



*****  Calling from JSF

<h:commandLink  action="#{tableModel.exportDoc( 'title' )}" >
                                            <p:graphicImage value="/images/exporter/word-logo.png" width="42" height="48"/>
                                        </h:commandLink>

No comments:

Post a Comment