XSLFO:按指定长度实现<fo:inline/>元素换行
问题原因
<fo:inline> 属于行内级元素,max-width 属性仅对块级元素生效,因此给它设置 max-width 不会起到限制宽度的作用。即使加上 wrap-option="wrap",行内元素也会优先占据可用的水平空间,直到空间耗尽才会换行,无法达到固定宽度内换行的预期效果。
解决方案
使用表格布局(<fo:table>)拆分布局为三个部分:左侧固定宽度文本块、中间点线填充区、右侧固定宽度文本块。每个文本块放在固定宽度的表格单元格中,既能实现指定宽度内自动换行,又能保持点线填充中间空间的布局逻辑。
修改后的代码如下:
<fo:list-item> <fo:list-item-label end-indent="label-end()"> <fo:block>1.</fo:block> </fo:list-item-label> <fo:list-item-body start-indent="body-start()"> <fo:block keep-with-next.within-page="always"> <fo:table table-layout="fixed" width="100%"> <!-- 左侧文本块:固定宽度10mm --> <fo:table-column column-width="10mm"/> <!-- 中间点线:自动填充剩余空间 --> <fo:table-column/> <!-- 右侧文本块:固定宽度10mm --> <fo:table-column column-width="10mm"/> <fo:table-body> <fo:table-row> <fo:table-cell padding-right="2mm"> <fo:block wrap-option="wrap"> A loooooooooooong text should wrap </fo:block> </fo:table-cell> <fo:table-cell> <fo:leader leader-pattern="dots" leader-pattern-width="1mm"/> </fo:table-cell> <fo:table-cell padding-left="2mm"> <fo:block wrap-option="wrap" text-align="right"> Another looooooong text should wrap </fo:block> </fo:table-cell> </fo:table-row> </fo:table-body> </fo:table> </fo:block> </fo:list-item-body> </fo:list-item>
效果说明
- 左侧单元格固定宽度10mm,内部文本超出宽度自动换行,保持左对齐;
- 中间单元格自动填充左右文本块的剩余空间,用点线铺满;
- 右侧单元格固定宽度10mm,内部文本超出宽度自动换行,保持右对齐(匹配你期望的右侧文本换行后对齐效果)。
内容的提问来源于stack exchange,提问作者inVoKer
相关产品推荐
相关产品推荐

