Template method example

Tai Bo
2 min readOct 31, 2021

In a project I work on, I need to programmatically fill out some PDF forms. The forms are very similar in terms of structure, content, and fields’ names. Using iTextSharp library, I can go through the fields in the PDF and set the values. The logic for filling out a PDF form can be generic, as I just need to know what are the fields’ names and the corresponding values of the PDF. I come up with a generic model and common logic for filing out the form, as demonstrated in the below snippets.

public abstract class PDFService<T> where T : class {

public abstract IDictionary<string, PdfFormFieldModel> ToFormDict(T formModel);


public virtual Stream FillPdf(PDFForm<T> formFillingRequest)
{
// ...codes omitted for brevity.

foreach (KeyValuePair<string, PdfFormFieldModel> entry in ToFormDict(formFillingRequest.Content as T))
{
// use iTextSharp to loop through the fields and set the corresponding values.
}
}
}

The PdfFormFieldModel is just a POCO to encapsulate a field in a PDF.

public class PdfFormFieldModel
{
public bool IsVisible { get; set; }
public string Name { get; set; }
public FieldType Type { get; set; }

public string Value { get; set; }

public PdfFormFieldModel(string fieldName)
{
Name = fieldName;
}

public PdfFormFieldModel(string fieldName, FieldType fieldType)
{
Name = fieldName;
Type =…

--

--

Tai Bo
Tai Bo

Written by Tai Bo

Backend developer in .NET core. I enjoy the outdoor, hanging out with good friends, reading and personal development.

No responses yet