What value to use for .MoveUp of canvas

You wonder

I dislike magic numbers in code so, my question is: Why 4? What expression would reveal this value of 4?

iText, when calculating the layout of some entity, retrieves properties from multiple sources, in particular the entity itself and its renderer. And it does not only ask them for explicitly set properties but also for defaults.

In the case at hand you see the default top margin value of the Paragraph class at work:

public override T1 GetDefaultProperty<T1>(int property) {
    switch (property) {
        case Property.LEADING: {
            return (T1)(Object)new Leading(Leading.MULTIPLIED, childElements.Count == 1 && childElements[0] is Image ? 
                1 : 1.35f);
        }

        case Property.FIRST_LINE_INDENT: {
            return (T1)(Object)0f;
        }

        case Property.MARGIN_TOP:
        case Property.MARGIN_BOTTOM: {
            return (T1)(Object)UnitValue.CreatePointValue(4f);
        }

        case Property.TAB_DEFAULT: {
            return (T1)(Object)50f;
        }

        default: {
            return base.GetDefaultProperty<T1>(property);
        }
    }
}

(iText Layout Paragraph method)

If you set the top margin of your paragraph to 0, you can simplify your code considerably:

public static void RegisterPdfImproved(string sourceFilename, string targetFilename, string registration)
{
    using (PdfDocument pdf = new PdfDocument(new PdfReader(sourceFilename), new PdfWriter(targetFilename)))
    using (Document document = new Document(pdf))
    {
        document.SetMargins(0, 0, 0, 0);
        Paragraph paragraph = new Paragraph(registration)
            .AddStyle(RegistrationStyle())
            .SetMarginTop(0);
        document.Add(paragraph);
    }
}

Without any magic values you now get

screen shot

Tags:

C#

.Net

Pdf

Itext7