首页 > 解决方案 > 在右对齐的 PdfPCell 中查找文本的起始 x 坐标

问题描述

我正在尝试在 iTextSharp 中完成格式化表格。

该表将是两列,左侧为左对齐,右侧为右对齐,右列和左列中的值之间有一条虚线。

由于我不希望使用固定宽度/等宽字体,因此到目前为止我的尝试是尝试识别左列中文本的结尾和右列中文本的开头,以在它们之间画一条虚线这两点,但是我正在努力获得这些坐标值。

string item = "Case #: ";
string value = record.CaseID;

// Initialize left cell of row
PdfPCell itemCell = new PdfPCell(new Phrase(item, regular));
itemCell.HorizontalAlignment = 0; // Left
caseSummaryTable.AddCell(itemCell);

// Resolve left cell in row to get end point
columnText.Go();
float xItemEnd = columnText.LastX;
float yItemEnd = columnText.YLine;

// Initialize right cell of row
PdfPCell valueCell = new PdfPCell(new Phrase(value, regular));
valueCell.HorizontalAlignment = 2; // Right
caseSummaryTable.AddCell(valueCell);

// Resolve right cell in row
// Attempt to get usable start X coordinate
columnText.Go();
float xValueStart = columnText.LastX; // ?
float yValueStart = columnText.YLine; // ?

LastX get 方法在两次使用中都返回 0,而 YLine 似乎返回一个可用值。有没有人提示确定我需要的坐标?

标签: c#itext

解决方案


                    string item = "Case #: ";
                    string value = record.CaseID;

                    // Initialize left cell of row
                    PdfPCell itemCell = new PdfPCell(new Phrase(item, regular));
                    itemCell.HorizontalAlignment = 0; // Left
                    itemCell.Border = Rectangle.NO_BORDER;
                    caseSummaryTable.AddCell(itemCell);

                    // Initialize right cell of row
                    PdfPCell valueCell = new PdfPCell(new Phrase(value, regular));
                    valueCell.HorizontalAlignment = 2; // Right
                    valueCell.Border = Rectangle.NO_BORDER;
                    caseSummaryTable.AddCell(valueCell);

                    // Calculate start and end of dotted-line
                    float xItemEnd = x0 + regular.BaseFont.GetWidthPoint(item, fontSize);
                    float xValueStart = x0 + xD - regular.BaseFont.GetWidthPoint(value, fontSize);
                    float rowBaseLine = columnText.YLine - leadingValue;

                    // Draw dotted-line from end of item text to start of value text
                    DottedLineSeparator dottedLine = new DottedLineSeparator();
                    dottedLine.Draw(contentByte, xItemEnd, rowBaseLine, xValueStart, rowBaseLine, rowBaseLine);

诀窍是从确定值列文本的结尾和值列文本的开始来获取字符串的计算宽度。


推荐阅读