iTextsharp 字符串之间的下划线

iTextsharp underline between strings

我正在使用 iTextsharp tp 创建 PDF。我有以下代码行来在 PDF 上显示文本。

var contentByte = pdfWriter.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 10);
var multiLine = " Request for grant of leave for ____2______days";
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, multiLine, 100, 540, 0);
contentByte.EndText();

我需要用下划线替换“____”。下划线应显示“2”。

请帮我解决这个问题。

我通过你的回答解决了这个问题。谢谢你..@Chris Haas

var baseFont = BaseFont.CreateFont(fontFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
var mainFont = new iTextSharp.text.Font(baseFont, 10);

//Our Phrase will hold all of our chunks
var p = new Phrase();

//Add the start text
p.Add(new Chunk("Request for grant of leave for ", mainFont));
var space1 = new Chunk("             ", FontFactory.GetFont(FontFactory.HELVETICA, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
                     p.Add(space1);
//Add our underlined text
var c = new Chunk("2", mainFont);
c.SetUnderline(0.1f, -1f);
p.Add(c);
var space1 = new Chunk("             ", FontFactory.GetFont(FontFactory.HELVETICA, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
                     p.Add(space1);
//Add our end text
p.Add(new Chunk(" days", mainFont));

//Draw our formatted text
ColumnText.ShowTextAligned(pdfWriter.DirectContent, PdfContentByte.ALIGN_LEFT, p, 100, 540, 0);

与其直接使用只允许您绘制字符串的 PdfContentByte,不如使用允许您访问 iText 抽象的 ColumnText,特别是具有 ChunkChunk =14=]方法就可以了。

//Create our base font and actual font
var baseFont = BaseFont.CreateFont(fontFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
var mainFont = new iTextSharp.text.Font(baseFont, 10);

//Our Phrase will hold all of our chunks
var p = new Phrase();

//Add the start text
p.Add(new Chunk("Request for grant of leave for ", mainFont));

//Add our underlined text
var c = new Chunk("2", mainFont);
c.SetUnderline(0.1f, -1f);
p.Add(c);

//Add our end text
p.Add(new Chunk(" days", mainFont));

//Draw our formatted text
ColumnText.ShowTextAligned(pdfWriter.DirectContent, PdfContentByte.ALIGN_LEFT, p, 100, 540, 0);