I am currently adding additions to someone else's code and have come across a PdfBuilder class which is using the PdfSharp dll. Up until this point the class has taken a type called BoxRequest in the constructor. like so:
public PdfDocument GenerateAddressLabelPdf(int id)
{
var box = _unitOfWork.BoxRepository.GetById(id);
var generator = new PdfBuilder(box);
return generator.BuildPdfDocument();
}
And the PdfBuilder class looks like this:
public class PdfBuilder
{
private readonly BoxRequest _boxRequest;
public PdfBuilder(BoxRequest boxRequest)
{
_boxRequest = boxRequest;
}
public PdfDocument BuildPdfDocument()
{
PdfDocument pdfDocument = new PdfDocument();
PdfPage page = pdfDocument.AddPage();
page.Orientation = PageOrientation.Landscape;
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Arial", 40, XFontStyle.Regular);
XTextFormatter tf = new XTextFormatter(gfx);
XRect rect = new XRect(0, (page.Height/4), page.Width, page.Height);
gfx.DrawRectangle(XBrushes.White, rect);
tf.Alignment = XParagraphAlignment.Center;
tf.DrawString(GetText(), font, XBrushes.Black, rect);
return pdfDocument;
}
private string GetText()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(_boxRequest.Name);
sb.AppendLine(_boxRequest.Department);
sb.AppendLine(_boxRequest.Location.LocationName);
return sb.ToString();
}
}
So as you can see the properties used in GetText are taken from the FileRequest type.
I now need to use this class again, this time for a new type called FileRequest, As soon as I made the call to this class and saw it only takes a BoxRequest I thought this could be a good thing to make generic.
So far I have changed the class like so:
public class PdfBuilder<T>
{
private readonly T _pdfType;
public PdfBuilder(T t)
{
_pdfType = t;
}
//additional class stuff
}
But now I am a little confused as to how I should make the GetText method generic, as I need to render certain lines for each and every type.
At this point I think I could pass the type to GetText and then check the type and append different lines based on type, but it seems like its no longer really generic?
GetTexthow about overriding theBoxRequestand the other classesToStringmethod and not caring about the type at all? You could the replaceGetText()with sth.input.ToString()otherwise, extractGetText()to an interface and let both of cour classes implement that in a proper wayFileRequestobject haveName,DepartamentandLocation.LocationNameproperties, just asBoxRequest? That is: is the way to print exactly the same or is it different?