右对齐PdfPCell中的文本

我有一个生成PDF发票的C#应用​​程序。 在此发票中是项目和价格表。 这是使用PdfPTablePdfPCell生成的。

我希望能够右对齐价格列,但我似乎无法 – 文本总是在单元格中左对齐。

这是我创建表的代码:

 PdfPTable table = new PdfPTable(2); table.TotalWidth = invoice.PageSize.Width; float[] widths = { invoice.PageSize.Width - 70f, 70f }; table.SetWidths(widths); table.AddCell(new Phrase("Item Name", tableHeadFont)); table.AddCell(new Phrase("Price", tableHeadFont)); SqlCommand cmdItems = new SqlCommand("SELECT...", con); using (SqlDataReader rdrItems = cmdItems.ExecuteReader()) { while (rdrItems.Read()) { table.AddCell(new Phrase(rdrItems["itemName"].ToString(), tableFont)); double price = Convert.ToDouble(rdrItems["price"]); PdfPCell pcell = new PdfPCell(); pcell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT; pcell.AddElement(new Phrase(price.ToString("0.00"), tableFont)); table.AddCell(pcell); } } 

有人可以帮忙吗?

我是iText的原始开发人员,我在书中解释了您遇到的问题。

您正在混合文本模式复合模式

文本模式下 ,使用Phrase作为构造函数的参数创建PdfPCell ,并在单元格级别定义对齐。 但是,您正在以复合模式工作。 一旦使用addElement()方法,就会触发此模式。 在复合模式下 ,将忽略在单元格级别定义的对齐(这可以解释您的问题)。 相反,使用单独元素的对齐。

如何解决您的问题?

通过以不同方式将Phrase添加到单元格,可以在文本模式下工作。 或者以复合模式工作并使用您为其定义对齐的Paragraph

复合模式优于文本模式的优点是同一单元格中的不同段落可以具有不同的对齐方式,而在文本模式下只能有一个对齐方式 。 另一个优点是您可以添加更多文本:您还可以添加图像,列表,表格…… 文本模式的一个优点是速度:处理单元格内容所需的处理时间更短。

 private static PdfPCell PhraseCell(Phrase phrase, int align) { PdfPCell cell = new PdfPCell(phrase); cell.BorderColor = BaseColor.WHITE; // cell.VerticalAlignment = PdfCell.ALIGN_TOP; //cell.VerticalAlignment = align; cell.HorizontalAlignment = align; cell.PaddingBottom = 2f; cell.PaddingTop = 0f; return cell; } 

这是我对user2660112的答案的推导 – 一种返回单元格以插入带边框和背景色的表格的方法,以及类似但无边框/无色的变体:

 private static PdfPCell GetCellForBorderedTable(Phrase phrase, int align, BaseColor color) { PdfPCell cell = new PdfPCell(phrase); cell.HorizontalAlignment = align; cell.PaddingBottom = 2f; cell.PaddingTop = 0f; cell.BackgroundColor = color; cell.VerticalAlignment = PdfPCell.ALIGN_CENTER; return cell; } private static PdfPCell GetCellForBorderlessTable(Phrase phrase, int align) { PdfPCell cell = new PdfPCell(phrase); cell.HorizontalAlignment = align; cell.PaddingBottom = 2f; cell.PaddingTop = 0f; cell.BorderWidth = PdfPCell.NO_BORDER; cell.VerticalAlignment = PdfPCell.ALIGN_CENTER; return cell; } 

然后可以像这样调用它们:

 Font timesRoman9Font = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9, BaseColor.BLACK); Font timesRoman9BoldFont = FontFactory.GetFont(FontFactory.TIMES_BOLD, 9, BaseColor.BLACK); Phrase phrasesec1Heading = new Phrase("Duckbills Unlimited", timesRoman9BoldFont); PdfPCell cellSec1Heading = GetCellForBorderedTable(phrasesec1Heading, Element.ALIGN_LEFT, BaseColor.YELLOW); tblHeadings.AddCell(cellSec1Heading); Phrase phrasePoisonToe = new Phrase("Poison Toe Toxicity Level (Metric Richter Scale, adjusted for follicle hue)", timesRoman9Font); PdfPCell cellPoisonToe = GetCellForBorderlessTable(phrasePoisonToe, Element.ALIGN_LEFT); tblFirstRow.AddCell(cellPoisonToe); 

也许是因为你正在混合添加细胞的不同方式? 您是否尝试过显式创建一个单元格对象,然后根据需要对其进行按摩,然后为每个单元格添加它?

您可以尝试的另一件事是设置垂直对齐以及水平对齐。