Tuesday, May 27, 2014

Generating PDF from HTML using itext & flying-saucer


public static void main(String[] args)
       {
              try
              {
                     String inputFile = "firstdoc.xhtml";
                     String outputFile = "firstdoc.pdf";
                     OutputStream os = new FileOutputStream(outputFile);

                     InputSource source = new InputSource(inputFile);
                     DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                     Document xhtmlContent = documentBuilder.parse(source);
                     ITextRenderer renderer = new ITextRenderer();
                     renderer.setDocument(xhtmlContent, null);
                     renderer.layout();
                     renderer.createPDF(os);

                     os.close();
              }
              catch (Exception e)
              {
                     e.printStackTrace();
              }

Tuesday, January 28, 2014

Hierarchical/Grouping enum :

We have different statuses and under each status there were sub statuses. We don’t want to check in switch or/if-else each sub statuses so we will check the main status.

public enum Status
{
       ACTIVE1(Group.ACTIVE, "active value 1"),
ACTIVE2(Group.ACTIVE, "active value 2"),
ACTIVE3(Group.ACTIVE, "active value 3"),
       BLOCKED1(Group. BLOCKED, "blocked value 1"),
BLOCKED2(Group. BLOCKED, "blocked value 2"),
BLOCKED3(Group. BLOCKED, "blocked value 3");

public enum Group
{
       ACTIVE, BLOCKED;
}

private String value;
private Group group;

private Status(Group group, final String value)
{
    this.value = value;
    this.group = group;
}

public String getValue()
{
       return this.value;
}
      
public Group getGroup()
{
       return this.group;
}
      
public boolean isInGroup(Group group)
{
    return this.group == group;
}
}

Using this enum in our conditional statements :

switch(statusObject.getGroup())
{
       case ACTIVE:
       case BLOCKED:
}

If(ACTIVE1.isInGroup(Group.ACTIVE)) // true


References: