Search code examples
javaxmlxsltxsl-fo

How to Render styles like font color and size which is present inside a span tag in xslt using xsl-fo?


I am generating pdf files based on the output from a rich text editor, some of the components like font color, font size for a specific word or a paragraph comes like

 <p>Hello Hi <strong>skansdjnsjc</strong>
 <span style="color:#ce181e"><em>cddsklncjkdsv</em></span>
 <span style="color:#ce181e">sdsadsad</span></p>

And in my xslt file I did a template match like

  <xsl:template match="span">     
    <xsl:variable name="color">
     <xsl:choose>
       <xsl:when test="@color">
         <xsl:value-of select="@color"/>
       </xsl:when>
       <xsl:otherwise>
         <xsl:text>black</xsl:text>
       </xsl:otherwise>
    </xsl:choose>
 </xsl:variable>
 </xsl:template>

But the required styles are not being rendered in the pdf file. Am I missing anything? or is there any solution to it.

Thanks For the help in advance !!!


Solution

  • In XSLT 2.0, you could extract the color from the style attribute like so

    <xsl:variable name="extractColor" select="tokenize(tokenize(@style, ';')[normalize-space(substring-before(., ':')) = 'color'], ':')[2]" />
    

    Then, to set your color variable (setting it to black if no color was extracted), do this....

    <xsl:variable name="color" select="($extractColor, 'black')[1]" />
    

    Of course, if you extended to extract other values, you could create a function.

    Try this XSLT

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" xmlns:my="my">
      <xsl:output method="html" indent="yes" html-version="5"/>
    
      <xsl:template match="span">
        <span>
            <xsl:variable name="color" select="(my:extract(@style, 'color'), 'black')[1]" />
            <xsl:value-of select="$color" />
        </span>
      </xsl:template>
    
      <xsl:function name="my:extract">
          <xsl:param name="text" />
          <xsl:param name="name" />
          <xsl:sequence select="tokenize(tokenize($text, ';')[normalize-space(substring-before(., ':')) = $name], ':')[2]" />
      </xsl:function>
    </xsl:stylesheet>