Search code examples
pdfsharpmigradoc

MigraDoc/PDFSharp TextFrame Centre Align


I am using a Paragraph inside a TextFrame to get the text orientation to be displayed upwards this is working to nearly how i would like it to, the final issue i have got is the text seems to be left aligned, i have tried setting the Paragraph alignment to centre this didn't have no affect and can't see an option to do this with a TextFrame. The text outputted will not be the same everytime.

This is what i currently have

enter image description here

This is what i want to acheive

enter image description here

The following is the code i am using to acheive this using MigraDoc

for (int i = 0; i < section2Items.Length; i++)
{
    TextFrame colXTextFrame = bothSection2ItemHeadersRow.Cells[i + 1].AddTextFrame();
    colXTextFrame.Orientation = TextOrientation.Upward;
    colXTextFrame.Height = new Unit(140);

    Paragraph colXParagraph = new Paragraph();
    colXParagraph.Format.Alignment = ParagraphAlignment.Center;
    colXParagraph.AddText(section2Items[i].Section2ItemTitle);
    colXTextFrame.Add(colXParagraph);

    bothSection2ItemHeadersRow.Cells[i + 1].Borders.Bottom = new Border() { Color = new MigraDoc.DocumentObjectModel.Color(255, 255, 255), Width = new MigraDoc.DocumentObjectModel.Unit(0), Style = MigraDoc.DocumentObjectModel.BorderStyle.None };
}

Solution

  • Here is a code example that should work.

    You can use the MarginLeft property of the TextFrame to shift it in the middle of the column.

    // Create the table 
    Table Table = section.AddTable();
    Table.Borders.Width = 0.5;
    
    // create 3 columns
    Column column1 = Table.AddColumn("4cm");
    Column column2 = Table.AddColumn("4cm");
    Column column3 = Tabl.AddColumn("4cm");
    
    
    // make the row
    Row row = Table.AddRow();
    
    
    for (int i = 0; i < 3; i++)
    {
        TextFrame t = row.Cells[i].AddTextFrame();
        t.Orientation = TextOrientation.Upward;
        t.Height = new Unit(140);
    
        // set the left margin to half of the column width
        t.MarginLeft = this.Tabelle.Columns[i].Width/2;
    
        Paragraph p = new Paragraph();
        p.Format.Alignment = ParagraphAlignment.Center;       
        p.AddText("Test_" + i.ToString());
    
        t.Add(p);
    }
    

    this produces the following output:

    enter image description here