views:

34

answers:

2

I need to style a ton of different elements (read: "cells") in a PDF using iTextSharp. Label, header, subheader, number, etc. Right now, I'm using three different methods for each cell type:

public static PdfPCell GetDefaultCell(string strText)
    {
        PdfPCell cell = new PdfPCell(new Phrase(strText, GetDefaultFont()));
        cell.Border = 0;
        return cell;
    }

public static PdfPCell GetDefaultCell(string strText, int iColspan)
    {
        PdfPCell cell = new PdfPCell(new Phrase(strText, GetDefaultFont()));
        cell.Border = 0;
        cell.Colspan = iColspan;
        return cell;
    }

public static PdfPCell GetDefaultCell(string strText, int iColspan, int iAlign)
    {
        PdfPCell cell = new PdfPCell(new Phrase(strText, GetDefaultFont()));
        cell.Border = 0;
        cell.Colspan = iColspan;
        cell.HorizontalAlignment = iAlign;
        return cell;
    }

Where "Default" is substituted with the cell type for each set of three methods. I don't think this scales. Especially if I end up with more than the 20 or 30 types I have now. What if I want to modify more than just the colspan and horizontalalignment attributes? Can I use delegates here? The only difference in my method calls is the name and the GetXFont() call within the method.

+1  A: 

You can pass a delegate to the method which returns the font:

public static PdfPCell GetCell(string strText, Func<Font> fontCreator)
{
    PdfPCell cell = new PdfPCell(new Phrase(strText, fontCreator()));
    cell.Border = 0;
    return cell;
}

var cell = GetCell("...", () => GetDefaultFont());

But why don't you simply pass the font directly to the method?

public static PdfPCell GetCell(string strText, Font font)
{
    PdfPCell cell = new PdfPCell(new Phrase(strText, font));
    cell.Border = 0;
    return cell;
}

var cell = GetCell("...", GetDefaultFont());
dtb
I think my biggest problem is the number of times it would have to be done. The PDF is huge and will continue to grow, and I'm trying to be as lazy as possible in styling these cells while still allowing for changes in the future. Both of these answer my questions, but is there any way to satisfy my laziness?
David
Can you give an example how you would like your code to look like? IMO my second solution is quite pretty.
dtb
agreed. i think im going with the delegate though so i only have to change the font once in the method call instead of potentially thousands.
David
A: 

You can certainly use delegates in your situation but the question is if it's really necessary. If the function GetDefaultFont returns a font that you want to use in your cell, you can simply pass this font as another argument (i.e. put the responsibility of calling it to the caller of your GetXXXCell method). Passing a delegate seems like an unnecessary abstraction here.

Thomas Wanner