C# iTextSharp:如何在单元格标签中实现部分文本加粗的混合字体
在iTextSharp中实现单元格内多样式文本的方法
直接给LabelText赋值纯文本无法实现部分内容加粗的效果,因为纯文本不支持样式区分。你需要用iTextSharp的Chunk和Phrase类来组合不同字体样式的内容,具体步骤如下:
- 定义字体样式
先创建普通字体和加粗字体的实例:
// 初始化基础字体(这里用Helvetica,编码CP1252) BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font regularFont = new Font(baseFont, 12, Font.NORMAL); // 普通样式字体 Font boldFont = new Font(baseFont, 12, Font.BOLD); // 加粗样式字体
- 组合带样式的文本内容
用Phrase容器来拼接不同样式的Chunk,每个Chunk可以单独设置字体,并用Chunk.NEWLINE实现换行:
Phrase formattedContent = new Phrase(); // 添加第一行的基础信息 formattedContent.Add(new Chunk($" {asseblynumber} EWAK {ewak} Qty.{quantidadepecas}", regularFont)); formattedContent.Add(Chunk.NEWLINE); formattedContent.Add(Chunk.NEWLINE); // Part Number 段落(标题加粗) formattedContent.Add(new Chunk("Part Number", boldFont)); formattedContent.Add(Chunk.NEWLINE); formattedContent.Add(new Chunk(Part_Number, regularFont)); formattedContent.Add(Chunk.NEWLINE); formattedContent.Add(Chunk.NEWLINE); // Assembly Name 段落 formattedContent.Add(new Chunk("Assembly Name", boldFont)); formattedContent.Add(Chunk.NEWLINE); formattedContent.Add(new Chunk(assemblyname, regularFont)); formattedContent.Add(Chunk.NEWLINE); formattedContent.Add(Chunk.NEWLINE); // Material 段落 formattedContent.Add(new Chunk("Material", boldFont)); formattedContent.Add(Chunk.NEWLINE); formattedContent.Add(new Chunk(material, regularFont)); formattedContent.Add(Chunk.NEWLINE); formattedContent.Add(Chunk.NEWLINE); // Fornecedor 段落 formattedContent.Add(new Chunk("Fornecedor", boldFont)); formattedContent.Add(Chunk.NEWLINE); formattedContent.Add(new Chunk(manufacturer, regularFont));
- 将组合内容设置到单元格/标签
把构建好的Phrase赋值给单元格(或你的label控件):
// 如果是PdfPCell,直接传入Phrase初始化 PdfPCell cell = new PdfPCell(formattedContent); // 如果是你原有的label控件,替换LabelText为Element赋值 // label.Element = formattedContent;
这样就能实现你想要的“标题加粗、内容普通”的排版效果。
内容的提问来源于stack exchange,提问作者TelesGomes
相关产品推荐
相关产品推荐

