Search code examples
xslt-2.0xsl-fosaxonapache-fop

Image resizing to fit on PDF page using Saxon HE Apache FOP XSL-FO XSLT 2.0


We are transforming XML to PDF using Saxon HE/ Apache FOP (XSLT 2.0). I would like to resize some of the images down to fit on the page. I understand to use the content-height and content-width "scale-down-to-fit" or "scale-to-fit" attributes but the height and width of the image is not available in the XML.
I need a way to access the image file dimensions in the XSLT.

Here is how a graphic might be depicted in the XML:

<graphic boardno="abcd.jpg" unitmeasure="in" inschlvl="0" delchlvl="0 />

Previously they were using xalan extensions (for v1.0 XSLT, we are upgrading to v.2)

xmlns:ii="xalan://ImageInfo" and xmlns:file="xalan://FileUtils"

and then in the XSL-FO:

<xsl:variable name="curGraphicUri">
    <xsl:value-of select="unparsed-entity-uri(@boardno)" />
</xsl:variable>

<xsl:variable name="imgProp">
    <xsl:value-of select="ii:setInputFile(string($curGraphicUri),72)" />
</xsl:variable>

<xsl:variable name="curFunctionStatus">
    <xsl:value-of select="substring-after(substring-before($imgProp,';'),'status:')" />
</xsl:variable>

So (I'm thinking) if I knew the equivalent functions in FOP, or another available extension, I should be able to figure out the rest. I have searched these forums and I haven't found a similar question.


Solution

  • With scale-down-to-fit (see https://www.w3.org/TR/xsl11/#content-height), you don't need to know the original size of the graphic because the XSL-FO formatter will know that anyway. If the full-size graphic will fit in the available space, then it will be rendered at 100% scale, otherwise the graphic will be reduced until it does fit within the available height/width.

    If you were using a formatter that also supports allowed-height-scale (see https://www.w3.org/TR/xsl11/#allowed-height-scale) and allowed-width-scale, then you could also control the scale factors that are used when the image is scaled down to fit. This can be useful, for example, to avoid Moiré patterns (see https://en.wikipedia.org/wiki/Moir%C3%A9_pattern) or to keep a consistent scale (or set of scales) between related graphics (e.g., a selection of screenshots of the menus of an application).