I have the following XML:
<sample>
<value1>This is one</value1>
<value2>Number two</value2>
<value4>Last value</value4>
</sample>
Using Apache FOP/XSL-FO I would like a PDF looking similar to this:
Value 1: This is one Value 2: Number two
Value 3: Value 4: Last value
Notice the spacing/padding between “Value 3:” and “Value 4:”.
The following transformation gives my the result I want. But it seems overly complicated (and might not perform very well for a real-life PDF with many values).
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:template match="sample">
<fo:root>
<fo:layout-master-set>
<fo:simple-page-master master-name="page-layout">
<fo:region-body margin="10mm" region-name="body"/>
</fo:simple-page-master>
</fo:layout-master-set>
<fo:page-sequence master-reference="page-layout">
<fo:flow flow-name="body">
<fo:block>
<xsl:variable name="pad">
<xsl:choose>
<xsl:when test="value1">5</xsl:when>
<xsl:otherwise>25</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<fo:inline padding-right="{$pad}mm">Value 1: <xsl:value-of select="value1"/></fo:inline>
Value 2: <xsl:value-of select="value2"/>
</fo:block>
<fo:block>
<xsl:variable name="pad">
<xsl:choose>
<xsl:when test="value3">5</xsl:when>
<xsl:otherwise>25</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<fo:inline padding-right="{$pad}mm">Value 3: <xsl:value-of select="value3"/></fo:inline>
Value 4: <xsl:value-of select="value4"/>
</fo:block>
</fo:flow>
</fo:page-sequence>
</fo:root>
</xsl:template>
</xsl:stylesheet>
Is there a simpler/better way to implement this?
Update:
I refactored the above into a template “field”:
<xsl:template name="field">
<xsl:param name="txt"/>
<xsl:param name="val"/>
<xsl:param name="pad"/>
<xsl:variable name="p">
<xsl:choose>
<xsl:when test="$val">5</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when test="$pad"><xsl:value-of select="$pad"/></xsl:when>
<xsl:otherwise>25</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<fo:inline padding-right="{$p}mm"><xsl:value-of select="$txt"/>:</fo:inline>
<fo:inline keep-with-previous="always" padding-right="5mm" font-weight="bold"><xsl:value-of select="$val"/></fo:inline>
</xsl:template>
Which can be used like this:
<xsl:call-template name="field">
<xsl:with-param name="txt">Value 1</xsl:with-param>
<xsl:with-param name="val"><xsl:value-of select="sample/value1"/></xsl:with-param>
</xsl:call-template>
The template takes a third optional parameter, pad. If specified its value will be used as padding.
David’s template (see accepted answer) uses a simpler if-contruct where the padding-right attribute is overwritten if needed.
Since this presumably isn’t being executed in a browser is there any reason not to use xslt2 (which would make it rather nicer) since you are using java anyway the free saxon 9 implementation would work well here.
But here’s an XSLT 1 version refactored a bit.