如何让PDF中自动换行文本的最后一行完全显示?
MigraDoc TextFrame 文本截断问题解决方法
问题描述
使用PDFsharp-MigraDoc 6.0.0-preview-3生成PDF报表时,遇到以下问题:
- 报表模板中的文本字段包含left、height、width、top属性,但Paragraph无位置与尺寸属性,必须将文本放入TextFrame内的Paragraph中。
- Paragraph的行数和高度不固定,当TextFrame的top位置加高度超出页面可打印区域时需要插入分页符,但Paragraph扩展为两行时,页面末尾的该行有时仅部分显示。
复现代码如下:
static Document CreateDocument() { // 创建新的MigraDoc文档 var document = new Document { }; // 向文档添加章节 var section = document.AddSection(); section.PageSetup.BottomMargin = 0; section.PageSetup.TopMargin = 0; for (int p = 1; p < 100; p++) { var textFrame = section.AddTextFrame(); textFrame.RelativeVertical = RelativeVertical.Line; textFrame.WrapFormat.DistanceTop = Unit.FromCentimeter(0.11); textFrame.Height = Unit.FromCentimeter(0.47); // 固定高度导致文本截断 var paragraph = textFrame.AddParagraph(); paragraph.Format.Font.Name = "Times New Roman"; paragraph.Format.Font.Size = 10; paragraph.AddText("Maksekorraldus 123456"); paragraph.Format.SpaceBefore = 0; paragraph.Format.SpaceAfter = 0; } return document; }
解决方法
由于无法提前获知Paragraph的高度,且MigraDoc未提供获取该高度的方法,可通过以下调整让所有文本行完整显示:
1. 取消TextFrame的固定高度,让其自动适配内容
移除TextFrame的固定高度设置,改用Unit.Empty让TextFrame根据内部Paragraph的高度自动调整:
textFrame.Height = Unit.Empty;
此设置既能保留RelativeVertical和WrapFormat.DistanceTop的定位逻辑,又不会因为固定高度限制Paragraph的显示空间。
2. 优化段落行间距,避免内容溢出
为Paragraph设置合理的最小行间距,确保单行文本不会被截断:
paragraph.Format.LineSpacingRule = LineSpacingRule.AtLeast; paragraph.Format.LineSpacing = Unit.FromPoint(12); // 对应10号字体,行间距设为12pt足够容纳文本
3. 确保TextFrame整体不被分页截断
给TextFrame添加KeepTogether设置,保证整个TextFrame的内容不会被分页拆分:
textFrame.Format.KeepTogether = true;
修改后的完整代码
static Document CreateDocument() { var document = new Document { }; var section = document.AddSection(); section.PageSetup.BottomMargin = 0; section.PageSetup.TopMargin = 0; for (int p = 1; p < 100; p++) { var textFrame = section.AddTextFrame(); textFrame.RelativeVertical = RelativeVertical.Line; textFrame.WrapFormat.DistanceTop = Unit.FromCentimeter(0.11); textFrame.Height = Unit.Empty; // 自动适配高度 textFrame.Format.KeepTogether = true; // 避免跨页截断 var paragraph = textFrame.AddParagraph(); paragraph.Format.Font.Name = "Times New Roman"; paragraph.Format.Font.Size = 10; paragraph.AddText("Maksekorraldus 123456"); paragraph.Format.SpaceBefore = 0; paragraph.Format.SpaceAfter = 0; paragraph.Format.LineSpacingRule = LineSpacingRule.AtLeast; paragraph.Format.LineSpacing = Unit.FromPoint(12); // 合理行间距 } return document; }
内容的提问来源于stack exchange,提问作者Andrus
相关产品推荐
相关产品推荐

