How do I center align text/images?

Q: I would like to insert text and images with specific horizontal
alignment like center. Is
that possible?
----
A: You can align/justify the text by taking into account the length of
the text run (returned by element.GetTextLength()). For example:

In C#
writer.WriteElement(element_builder.CreateTextBegin(Font.Create(doc,
font), font_size)); Element element =
element_builder.CreateTextRun("My text");

// To right justify
element.SetTextMatrix(1, 0, 0, 1, box_width - element.GetTextLength(),
pos_Y);

// To 'center' justify
// element.SetTextMatrix(1, 0, 0, 1, (box_width -
element.GetTextLength())/2, pos_Y); writer.WriteElement(element);
writer.WriteElement (element_builder.CreateTextEnd())

In C++:

writer.WriteElement(element_builder.CreateTextBegin(Font::Create(doc,
font), font_size)); Element element =
element_builder.CreateTextRun("My Text");

// To right justify
element.SetTextMatrix(1, 0, 0, 1, box_width – element.GetTextLength(),
pos_Y);

// To 'center' justify
// element.SetTextMatrix(1, 0, 0, 1, (box_width –
element.GetTextLength())/2, pos_Y); writer.WriteElement(element);
writer.WriteElement(element_builder.CreateTextEnd())

To center align images you only need to make sure that the translation
component in the transformation matrix is set to a correct location.

Matrix2D mtx = Matrix2D(width, 0, 0, height, center_x - width/2.0,
center_y + height/2.0); Element element = f.CreateImage(img,
mtx); ....

Q: How do you get the value of box-width and Pos-Y in the above
snippet?
----
A: Box width is the width of the text box' - the rectangle in which
you are placing the text. Pos_y is the lower Y coordinate of the same
'text box'.

So is the text box is defined as Rect rect = new Rect (10, 100, 200,
150);

text box := rect.Width(); // 190
pos_Y := rect.get_y1(); // 100