You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PDFsharp生成PDF目录:如何动态设置文本间的点?

在PDFsharp中动态生成目录的点线分隔

我之前做PDF生成时也碰到过一模一样的需求,核心其实就是靠文本宽度测量来动态计算需要填充的点数量,让点刚好填满标题和页码之间的空隙。下面是具体的实现思路和代码示例:

核心步骤拆解

  1. 先定好页面的边距规则,比如左侧留50单位边距,右侧也留50单位,页码固定靠右侧对齐
  2. 对每个目录项,先测量标题文本的实际宽度
  3. 计算标题结束位置到页码起始位置的空白区域宽度
  4. 根据单个点的宽度,算出需要多少个点才能填满这个空白
  5. 依次绘制标题、点、页码,同时给整个目录项添加跳转链接

代码示例

假设你已经初始化好了XGraphics gfx对象和统一的XFont(比如用Arial 12号常规字体),页面对象是page:

// 定义基础布局参数
double leftMargin = 50;
double rightMargin = 50;
double currentY = 100; // 目录区域的起始Y坐标

// 模拟你的动态目录数据,替换成实际业务数据即可
var tocItems = new List<(string Title, int TargetPage, XRect TargetArea)>
{
    ("Text", 1, new XRect(0, 0, page.Width, page.Height)),
    ("Text2", 2, new XRect(0, 0, page.Width, page.Height)),
    ("Chapter4", 10, new XRect(0, 0, page.Width, page.Height))
};

foreach (var item in tocItems)
{
    // 1. 测量标题文本的宽度
    double titleWidth = gfx.MeasureString(item.Title, font).Width;
    
    // 2. 确定页码的绘制位置(靠右对齐)
    string pageNumText = item.TargetPage.ToString();
    double pageNumWidth = gfx.MeasureString(pageNumText, font).Width;
    double pageNumX = page.Width - rightMargin - pageNumWidth;
    
    // 3. 计算需要填充点的区域宽度
    double dotsAreaWidth = pageNumX - (leftMargin + titleWidth);
    
    // 4. 计算需要的点数量并生成点字符串
    double singleDotWidth = gfx.MeasureString(".", font).Width;
    int dotCount = (int)(dotsAreaWidth / singleDotWidth);
    string dots = new string('.', dotCount);
    
    // 5. 依次绘制标题、点、页码
    gfx.DrawString(item.Title, font, XBrushes.Black, new XPoint(leftMargin, currentY));
    gfx.DrawString(dots, font, XBrushes.Black, new XPoint(leftMargin + titleWidth, currentY));
    gfx.DrawString(pageNumText, font, XBrushes.Black, new XPoint(pageNumX, currentY));
    
    // 6. 添加文档跳转链接(覆盖整个目录项区域)
    XRect tocItemRect = new XRect(
        leftMargin, 
        currentY, 
        page.Width - leftMargin - rightMargin, 
        font.GetHeight(gfx)
    );
    gfx.AddDocumentLink(tocItemRect, item.TargetPage - 1); // PDFsharp页码从0开始,注意减1
    
    // 下移到下一个目录项的位置,加一点行间距
    currentY += font.GetHeight(gfx) + 6;
}

注意细节

  • 一定要保证标题、点、页码用完全相同的字体和字号,不然宽度测量会出错,点的数量就不准了
  • 如果想要更细腻的点线,也可以用XGraphics.DrawLine画虚线,但文本形式的点更贴近你要的示例效果
  • 记得PDFsharp的页面索引是从0开始的,所以添加跳转链接时要把你的实际页码减1

内容的提问来源于stack exchange,提问作者B.Dorsey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:28:52