Search code examples
c#itext7

iText 7 - cell text rotation


I am using iText 7 C# to build a pdf. Here is my issue.. I am trying to add a date to the last row. Since I do not have much space available I am trying to rotate it vertically.. but the text is wrapping to the next line. Also, I wanted the text to be exactly center of cell (vertically and horizontally after the rotation). Can I have the rotation slightly fall to the right like '/'?

// add signed date row
table.AddCell(new Cell().Add(new Paragraph("")).SetWidth(UnitValue.CreatePercentValue(1 * 5)).SetBorder(Border.NO_BORDER));
table.AddCell(new Cell().Add(new Paragraph("")).SetWidth(UnitValue.CreatePercentValue(7 * 5)).SetBorder(Border.NO_BORDER));
index = 0;
foreach (var month in months)
{
    var dateCell = new Cell().SetWidth(UnitValue.CreatePercentValue(1 * 5))
                            .Add(new Paragraph("3/5/23")).SetFontSize(8);
    dateCell.SetRotationAngle(Math.PI/2);
    table.AddCell(dateCell);
    index++;
 }

enter image description here


Solution

  • This should do the job, including the TextAlignment and preventing of word wrap

    var dateCell = new Cell().SetWidth(UnitValue.CreatePercentValue(1 * 5))
            .SetHeight(UnitValue.CreatePercentValue(30)) // Adjust the cell height as needed
            .SetTextAlignment(TextAlignment.CENTER) // Set text alignment to center
            .SetPaddingBottom(10) // Adjust the bottom padding as needed
            .Add(new Paragraph("3/5/23")).SetFontSize(8);
    
        // Adjust rotation angle to make it fall slightly to the right
        dateCell.SetRotationAngle(Math.PI / 4);
    

    Alternative from comment

    var paragraph = new Paragraph("3/5/23");
    
    // Adjust rotation angle to make it fall slightly to the right    
    paragraph.SetRotationAngle(Math.PI / 4);
    
    var dateCell = new Cell().SetWidth(UnitValue.CreatePercentValue(1 * 5))
            .SetHeight(UnitValue.CreatePercentValue(30)) // Adjust the cell height as needed
            .SetTextAlignment(TextAlignment.CENTER) // Set text alignment to center
            .SetPaddingBottom(10) // Adjust the bottom padding as needed
            .Add(paragraph).SetFontSize(8);