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

如何使用PdfContentByte设置可定位的文本下划线?

解决方案:实现自定义位置的下划线文本

问题分析

  • 你用PdfContentByte的代码无效,是因为ShowTextAligned传入Phrase时,Chunk的下划线样式不会被识别——该方法在文本模式下需要直接设置字体属性,而非通过Phrase传递。
  • 你用Chunk的代码无法定位,是因为直接document.Add()会按流式布局自动排版,不支持自定义绝对位置。

方法1:用PdfContentByte实现自定义位置下划线文本

手动设置带下划线的字体,通过文本矩阵指定位置后绘制文本:

// 获取PdfContentByte实例
PdfContentByte contentByte = writer.DirectContent;
// 定义带下划线的字体
Font font = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.UNDERLINE);

contentByte.BeginText();
// 设置字体和大小
contentByte.SetFontAndSize(font.BaseFont, font.Size);
// 设置文本绝对位置(x=80, y=770)
contentByte.SetTextMatrix(80, 770);
// 绘制目标文本
contentByte.ShowText("Electronic Generate Random Number Form");
contentByte.EndText();

方法2:用Chunk+ColumnText实现自定义位置下划线文本

利用ColumnText可以将带样式的Chunk定位到指定坐标,同时保留下划线效果:

BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\Calibri.ttf", "Identity-H", BaseFont.EMBEDDED);
var font1 = new Font(baseFont, 16, Font.BOLD | Font.UNDERLINE, BaseColor.BLACK);
var font2 = new Font(baseFont, 14, Font.BOLD | Font.UNDERLINE, BaseColor.BLACK);

Chunk chunk1 = new Chunk(OrderInformation.Text, font1);
Chunk chunk2 = new Chunk(Label2.Text, font2);

// 将chunk1定位到(x=100, y=750),左对齐
ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_LEFT, new Phrase(chunk1), 100, 750, 0);
// 将chunk2定位到(x=100, y=720),左对齐
ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_LEFT, new Phrase(chunk2), 100, 720, 0);

内容的提问来源于stack exchange,提问作者syaq

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 09:32:39