如何在iText 7.2.1中实现图文混合段落的均匀行间距
解决iText 7.2.1中混合文本与图标时固定行间距失效的问题
问题原因
SetFixedLeading()仅对纯文本段落生效,默认情况下图片元素的垂直对齐基于文本基线,且图片实际高度会撑开所在行的最小高度,导致该行行间距突破固定leading值的限制。
解决方案
通过调整图标的垂直对齐方式,并压缩其垂直占位空间,让图标适配固定行高:
- 设置图标垂直居中对齐,避免基线对齐导致的行高被拉高
- 通过负边距抵消图标自身高度带来的额外行高,或直接限制图标高度不超过固定leading值
修改后的代码
using iText.Kernel.Colors; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas; using iText.Layout; using iText.Kernel.Pdf.Xobject; using iText.Layout.Element; using iText.Kernel.Geom; using iText.Kernel.Font; using iText.IO.Font; using iText.Layout.Properties; namespace iTextTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { var writer = new PdfWriter("test.pdf"); var pdf_doc = new PdfDocument(writer); var doc = new Document(pdf_doc, iText.Kernel.Geom.PageSize.DEFAULT, false); // 生成不同字号的文本 var mixed_paragraph = new Paragraph(); for (int i = 0; i < 100; i ++) { var style = new Style(); var size = (Math.Sin(i) + 2) * 10; style.SetFontSize((float)size); mixed_paragraph.Add(new Text("A").AddStyle(style)); } // 创建20x20的红色图标 var bounds = new iText.Kernel.Geom.Rectangle(0, 0, 20, 20); var xobj = new PdfFormXObject(bounds); var pdf_canvas = new PdfCanvas(xobj, pdf_doc); pdf_canvas.SetFillColor(ColorConstants.RED); pdf_canvas.Rectangle(0, 0, 20, 20); pdf_canvas.Fill(); var icon = new iText.Layout.Element.Image(xobj); // 核心修改:适配固定行间距 icon.SetVerticalAlignment(VerticalAlignment.MIDDLE); // 负边距抵消图标高度带来的行高膨胀,值可根据实际情况调整 icon.SetMarginTop(-5f); icon.SetMarginBottom(-5f); // 若图标尺寸过大,可直接限制高度为固定行高值 // icon.SetHeight(10f); mixed_paragraph.Add(icon); // 设置固定行高 mixed_paragraph.SetFixedLeading(10); doc.Add(mixed_paragraph); doc.Close(); pdf_doc.Close(); writer.Close(); MessageBox.Show("OK"); } } }
关键说明
VerticalAlignment.MIDDLE:让图标与文本在垂直方向居中对齐,避免图标底部锚定文本基线导致行高被强制拉高- 负边距调整:通过
SetMarginTop和SetMarginBottom的负值,抵消图标自身高度超出固定行高的部分,让整行高度严格遵循SetFixedLeading(10)的设置 - 强制图标高度:如果图标本身尺寸远大于固定行高,直接用
SetHeight(10f)将图标缩小至行高范围内,是更直接的解决方案
内容的提问来源于stack exchange,提问作者landings
相关产品推荐
相关产品推荐

