How to Generate Table-of-Figures Dot Leaders in a PdfPCell for the Last Line of Wrapped Text

牧云@^-^@ 提交于 2019-11-28 12:55:29

First things first: +1 for your question and the answer you provided yourself.

But...

Although your answer may work, there is a better way to achieve your goal. I've written a small sample called DottedLineLeader as an alternative that will be much easier to maintain. This example uses the DottedLineSeparator wrapped in a Chunk object.

Take a look at how such a chunk separator is used:

Chunk leader = new Chunk(new DottedLineSeparator());
Paragraph p;
p = new Paragraph("This is a longer title text that wraps");
p.add(leader);

When we add this Paragraph to a PdfPCell, we get the following effect:

The dots in the dotted line are not '.' characters. Instead it's an actual line (vector data) with a specific dash pattern. Using this approach instead of your own, will significantly reduce the number of lines in your code, use less CPU and result in cleaner PDFs.

Here's one solution that suffices the question requirements.

Each PdfPCell object has a .Column property that "Returns the list of composite elements of the column". Its property ColumnText.LastX returns "The X position after the last line that has been written". This is the position where we want the leader dots to start.

This work can be done in the PdfPTablEvent.TableLayout handler where all the cell positions are known.

class TofEvents : IPdfPTableEvent {
    public void TableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases)
    {
      // do the work here 
    }
 }

Because we know where the last line of the text ends on the page, and where the right side the cell is, we can fill that space with dots.

General calculation for creating the proper number of dots for a particular cell is:

// You'll have to get references to things you need from the handler method args - 
float ptXCellLeft = GetLeftSideOfCellFromIncomingWidthsArgument();
PdfPCell cell = GetCurrentCellFromIncomingCellsArgument(); 

// the math - 
Font f = getTheFontToUse(); // for measuring the text size in this font 
float leaderDotSymbolWidth = f.BaseFont.GetWidthPoint(".", f.Size);
float leaderDotsWidth = cell.Width - (cell.Column.LastX - ptXCellLeft);
string strLeaderDotsFillText = ".".Repeat(Convert.ToInt32(leaderDotsWidth / leaderDotSymbolWidth));

The resulting strLeaderDotsFillText should fit nicely into the last line's space.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!