Unable to vertically align text in table cell with itextsharp

后端 未结 3 668
别跟我提以往
别跟我提以往 2021-01-18 19:07

I can not figure out how to vertically align text in table cell. horizontal alignment is ok. I use itextsharp to generate pdf. Alignment should be applied to cells in table

3条回答
  •  醉话见心
    2021-01-18 20:08

    You have a complex example that appears to be using nested tables and extension methods. As Alexis pointed out, the VerticalAlignment is the correct property to use. Below is a full working example of this. I recommend getting rid of your extension method for now and just starting with this example.

    //Our test file to output
    var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
    
    //Standard PDF setup, nothing special here
    using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
        using (var doc = new Document()) {
            using (var writer = PdfWriter.GetInstance(doc, fs)) {
                doc.Open();
    
                //Create our outer table with two columns
                var outerTable = new PdfPTable(2);
    
                //Create our inner table with just a single column
                var innerTable = new PdfPTable(1);
    
                //Add a middle-align cell to the new table
                var innerTableCell = new PdfPCell(new Phrase("Inner"));
                innerTableCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                innerTable.AddCell(innerTableCell);
    
                //Add the inner table to the outer table
                outerTable.AddCell(innerTable);
    
                //Create and add a vertically longer second cell to the outer table
                var outerTableCell = new PdfPCell(new Phrase("Hello\nWorld\nHello\nWorld"));
                outerTable.AddCell(outerTableCell);
    
                //Add the table to the document
                doc.Add(outerTable);
    
                doc.Close();
            }
        }
    }
    

    This code produces this PDF:enter image description here

提交回复
热议问题