birwin 的答案就是行不通。 ColumnText 对齐方式只接受水平对齐方式。这一直有效,直到 ColumnText 文本处于文本模式。当您调用 ColumnText.AddElement 时,ColumnText 切换到 CompositMode 并且对齐无效。
如果你真的想在 ColumnText 中垂直对齐,那么你必须创建一个具有对齐内容的内容,并且必须添加到 ColumnText。只有 Table 和 Cell 是垂直对齐的正确对象。
所以首先我们必须创建一个表格,其中包含一列和一个单元格。并将单元格的大小设置为与列文本大小相同。
其次,必须将此表添加到 ColumntText
这是我的代码:
// create doc
var pdfDoc = new Document( PageSize.A4 );
var pdfWriter = PdfWriter.GetInstance( pdfDoc, new FileStream( Path.Combine( Path.GetTempPath(), "test.pdf" ), FileMode.Create ) );
pdfDoc.Open();
var canvas = pdfWriter.DirectContent;
canvas.SaveState();
canvas.Rectangle( 100, 100, 100, 100 );
canvas.SetRgbColorFill( 255, 128, 128 );
canvas.Fill();
canvas.RestoreState();
// create font
BaseFont bfTimes = BaseFont.CreateFont( BaseFont.TIMES_ROMAN, BaseFont.CP1252, false );
Font times = new Font( bfTimes, (float)10, Font.ITALIC, new BaseColor( (int)232434 ) );
Phrase myText = new Phrase( new Chunk( "Hello World", times ) );
ColumnText ct = new ColumnText( canvas );
/* wrong birwin code :
ct.SetSimpleColumn( myText, 100, 100, 200, 200, ct.Leading, Element.ALIGN_BOTTOM );
*/
// new working code: crreate a table
PdfPTable table = new PdfPTable( 1 );
table.SetWidths( new[] { 1 } );
table.WidthPercentage = 100;
table.AddCell( new PdfPCell( myText )
{
HorizontalAlignment = Element.ALIGN_RIGHT,
VerticalAlignment = Element.ALIGN_BOTTOM,
FixedHeight = 100
} );
ct.SetSimpleColumn( 100, 100, 200, 200 );
ct.AddElement( table );
ct.Go();
pdfDoc.Close();