xsltxsl-foapache-fop

XSL-FO Region-Body background image


I have to add a background image to a page and add some text/content on the page. I am new to XSL-FO so I did some research. It looks like I need to use Region-Body and add the image using background-image attribute.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:fox="http://xmlgraphics.apache.org/fop/extensions">

  <!-- Entry point -->
  <xsl:template match="/">
    <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:fox="http://xmlgraphics.apache.org/fop/extensions">

      <fo:layout-master-set>

        <fo:simple-page-master master-name="cover-page" page-height="21cm" page-width="29.7cm">
          <fo:region-body background-image="url('Cover.jpg')" fox:background-image-width="29.7cm" fox:background-image-height="21cm"/>
        </fo:simple-page-master>

      </fo:layout-master-set>


      <!-- Cover Page -->
      <fo:page-sequence master-reference="cover-page" force-page-count="no-force" format="i">
        <fo:flow flow-name="xsl-region-body">
          <xsl:call-template name="tpltCoverPage"/>
        </fo:flow>
      </fo:page-sequence>


    </fo:root>
  </xsl:template>

  <!-- Cover Page -->
  <xsl:template name="tpltCoverPage">
    <fo:block></fo:block>
  </xsl:template>

</xsl:stylesheet>

The image appears as a background however it is 1700 * 1200 so the image is zoomed in and I can only see partial image in the background. Is there anyway I can zoom out the image so it fits the page height and width (without altering the actual image)?


Solution

  • Using only XSL 1.1 properties, you can position a background image but you can't scale it.

    FOP has extension properties for setting the width and height of a background image: https://xmlgraphics.apache.org/fop/2.3/extensions.html#backgroundimages

    (AH Formatter can do that and more: https://www.antenna.co.jp/AHF/help/en/ahf-ext.html#background)


    Formatting just the XSL-FO from your sample worked for me with FOP 2.2:

    <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"
         xmlns:fox="http://xmlgraphics.apache.org/fop/extensions">
      <fo:layout-master-set>
        <fo:simple-page-master master-name="cover-page"
                   page-height="21cm" page-width="29.7cm">
          <fo:region-body background-image="url('Cover.jpg')"
              fox:background-image-width="29.7cm"
              fox:background-image-height="21cm"/>
        </fo:simple-page-master>
      </fo:layout-master-set>
    
      <!-- Cover Page -->
      <fo:page-sequence master-reference="cover-page"
            force-page-count="no-force" format="i">
        <fo:flow flow-name="xsl-region-body">
          <fo:block></fo:block>
        </fo:flow>
      </fo:page-sequence>
    </fo:root>