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

使用PdfFileWriter创建带下划线字体报错,寻求解决方案

解决PdfFileWriter创建带下划线字体的错误问题

错误原因

PDF字体资源本身不存储下划线、删除线这类文本修饰样式,这些属于文本渲染阶段的属性,因此PdfFileWriter.PdfFont.CreatePdfFont方法不支持通过FontStyle.Underline参数创建带下划线的字体,会抛出error:font resource cannot have underline or strikeout错误。

可行方案

方案1:使用内置文本下划线方法

先创建常规字体,再在绘制文本时指定下划线样式:

// 创建基础常规字体
PdfFileWriter.PdfFont font = PdfFileWriter.PdfFont.CreatePdfFont(pdfDocument, FontName, FontStyle.Regular);
// 绘制文本时启用单下划线
pdfPage.DrawText(font, 12, 50, 50, "带下划线的文本", TextUnderline.Single);

方案2:手动绘制自定义下划线

如果需要调整下划线的粗细、颜色或位置,可手动绘制线条配合文本:

string targetText = "自定义下划线文本";
float fontSize = 14;
float xPos = 50;
float yPos = 50;

// 创建基础字体
PdfFileWriter.PdfFont font = PdfFileWriter.PdfFont.CreatePdfFont(pdfDocument, FontName, FontStyle.Regular);
// 获取文本的尺寸信息,用于计算下划线位置和长度
PdfFileWriter.PdfRectangle textBounds = font.TextRect(fontSize, targetText);

// 先绘制文本
pdfPage.DrawText(font, fontSize, xPos, yPos, targetText);
// 计算下划线的Y坐标(基线下方偏移,可根据需求调整)
float underlineY = yPos - textBounds.Bottom - 1.2f;
// 绘制下划线线条(参数依次为起点X、起点Y、终点X、终点Y、线宽、颜色)
pdfPage.DrawLine(xPos, underlineY, xPos + textBounds.Width, underlineY, 0.6f, PdfColor.DarkGray);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 07:18:18