问题
For some reason my spaces aren't being preserved in my final PDF after xslt. My desired output is:
Static
text bold.
Here's my xslt template:
<xsl:preserve-space elements="*" />
<xsl:strip-space elements="" />
<xsl:template match="coverPage">
<fo:block font-size="12pt" color="black" text-align="center">
<xsl:text>
Static


text
</xsl:text>
</fo:block>
<fo:block font-size="12pt" color="black" text-align="center" font-weight="bold">
<xsl:text>
bold.
</xsl:text>
</fo:block>
</xsl:template>
回答1:
I think there are a few issues with your XSLT:
- there is no need to enclose the text inside
xsl:text
elements, as those text nodes are not composed only of whitespace characters and therefore will never be stripped (see Whitespace stripping for more details) - for the same reason, there is no need to use
xsl:preserve-space
andxsl:strip-space
, unless of course you need them for other reasons - preserving linefeeds in the transformation from XML to XSL-FO is just the (required) first step, but then you must preserve them during the processing of the XSL-FO file; in order to do this, you must use the linefeed-treatment property:
linefeed-treatment="preserve"
- a literal linefeed is equivalent to a


entity, so in your input you have 3 linefeeds between "Static" and "text", which will produce two empty lines when preserved; if that's not what you want, you have to remove some of them - the words "text" and "bold" are inside two different
fo:block
elements, so this means they will always be on different lines; if you want them to be placed one beside the other, those words must be insidefo:inline
elements instead (and there must be an outerfo:block
to contain them)
A final word of warning
While looking at an FO file the difference between a preserved linefeed and an ignored one is not immediately apparent, as it boils down to the presence of the linefeed-treatment
attribute in an ancestor element (which could be quite far from the text node itself).
Clearer ways to force a line break in a specific position include:
- using different
fo:block
elements, each one containing the text that should create a line (or several ones)
<fo:block>Static</fo:block>
<fo:block>text <fo:inline font-weight="bold">bold.</fo:inline></fo:block>
- using an empty
fo:block
where a line break should be
<fo:block>
Static
<fo:block/>
text <fo:inline font-weight="bold">bold.</fo:inline>
</fo:block>
来源:https://stackoverflow.com/questions/36802214/xslt-new-lines-not-being-preserved