Title: Apache(tm) FOP: XSL-FO Input [fopLatest_config]: 2.5/configuration.html #Apache™ FOP: XSL-FO Input Basic Help for Using XML, XSLT, and XSL-FO ## Overview { #overview} Apache™ FOP uses XSL-FO as input. It is the responsibility of the user to make sure that the XSL-FO submitted to FOP is correct. The tutorial items presented here are not comprehensive, but are of the FAQ variety. Another good FAQ is [Dave Pawson's XSL FAQ](http://www.dpawson.co.uk/xsl/). ## XML Issues { #xml} ### Special Characters { #xml-special-chars} When entering special (non-ASCII) characters in XML, the general rule is to use the applicable Unicode character instead of trying to use a character entity as you would with HTML. Remember that HTML is an SGML document type. SGML has a limited character set, which requires it to use character entities to represent special characters. One of the improvements of XML over SGML (and thus HTML) is native support for Unicode. Basic XML has only a handful of character entities, primarily because it doesn't really need more. Entities such as `ü` (u with an umlaut), which work in HTML, will be flagged as undefined entities unless you define them yourself in your DTD. Use the corresponding Unicode character instead. A list of predefined HTML entities and their Unicode codepoints can be found at [Character entity references in HTML 4](http://www.w3.org/TR/html4/sgml/entities.html). One common example is ` `, used to obtain a non-breaking space in HTML. In XML, use ` ` or ` ` instead. For other non-ASCII characters, such as the Euro symbol, checkbox, etc., see the [Unicode Reference By Name](http://www.unicode.org/charts/charindex.html) document that is found at the [Unicode Consortium](http://www.unicode.org) site. After finding the correct Unicode codepoint to represent the character, use [XML Character References](http://www.w3.org/TR/2000/REC-xml-20001006#sec-references) to put the character into your source XML, XSLT or FO. See the non-breaking-space comments above for an example of the syntax using decimal notation. The following hexadecimal example will result in a Euro sign: `€` Getting your XML correctly encoded is only part of the job. If you want the character to display or print correctly (and you probably do), then the selected font must contain the necessary glyph. Because of differences between font encoding methods, and limitations in some font technologies, this can be a troublesome issue, especially for symbol characters. The FOP example file [Base-14 Font Character Mapping](fo/fonts.fo.pdf) is a very useful resource in sorting these issues out for the Base-14 fonts. For other fonts, use font editing sofware or operating system utilities (such as the Character Map in most Windows platforms) to determine what characters the font supports. An alternative to encoding the character and making it available through a font is to use an embedded graphic to represent the character: GIF, PNG, SVG, etc. ### Entity Characters { #xml-entity-chars} The handful of basic XML character entities that do exist are the ampersand, apostrophe, less-than, greater-than, and single-quote characters. These are needed to distinguish markup tags from content, and to distinguish character entities from content. To avoid parser complaints about illegal characters and entities in your input, ensure that ampersands in text and attributes are written as `&`, "<" is written as `<`, and ">" as `>`. It is not necessary everywhere, but it is wise to do so anyway, just to be sure. Most XML parsers will provide a line number and sometimes a column number for offending characters. Review the [XML Specification](http://www.w3.org/XML/) or a good tutorial for details of the XML file format. ### Encoding Issues { #xml-encoding} If the parser complains about illegal bytes or characters in the input, or there are unexpected characters in the output, this is usually the result of a character encoding problem. See the [XSL FAQ](http://www.dpawson.co.uk/xsl) for additional information. Many software packages that produce XML, including XSLT processors, use UTF-8 encoding as a default. If you view their output with something not aware of the encoding, like Notepad for Win95/98/ME/NT, funny characters are displayed. A � is a giveaway. ## XSLT Issues { #xslt} ### Current Date and Time { #xslt-date} XSL-FO does not currently have a function for retrieving the current date and time. However, in some cases, XSLT can be used to place the current date and time into the XSL-FO document as it is generated. One possibility is to use the [exslt date and time extension](http://exslt.org/date/index.html). Another possibility is to use java or javascript (or perhaps some other language). Here is an example, using java, that works with Xalan. First, create the appropriate namespace: :::xml Next, use the java language to retrieve and format the current date and time. Here is an example template: :::xml ## XSL-FO Issues { #xsl-fo} ### Vertical Centering { #fo-center-vertical} To vertically center an image, table, or other item, use display-align="center". See [display-align Compliance](compliance.html#fo-property-display-align) for implementation status. Here is a small, self-contained document centering an image on a page: :::xml ### Horizontal Centering (Tables) { #fo-center-table-horizon} To center a table horizontally, one possibility is to add one column on the left and one on the right which pad the table so that the visible part is centered: :::xml foo If your table is more complicated, or if defining borders on individual cells becomes too much work, use the code above and nest your table within the middle cell. ### Right-Aligning (Tables) { #fo-right-align-table-horizon} To right-align a table, you can use the same approach as above for centering tables. Just remove the last table-column element which causes all the left-over space not used by the columns with a fixed column-width to be assigned to the first column which effectively right-aligns the table. ### Recto/Verso Static Content Differences { #fo-oddeven} One frequent request is that static content be different between recto pages (right-side or odd-numbered pages typically) and verso pages(left-side or even-numbered pages typically). For example, you may wish to place the page number on the "outer" side of each page. There are examples in the FO distribution and in the [XSL FAQ FO section](http://www.dpawson.co.uk/xsl/sect3/index.html). First, define a page master with alternating pages masters for odd and even pages. Then specify appropriate regions in these page masters, giving them different names. Use these names to put different static content in these regions. Here is a self-contained demonstration: :::xml ### Making the First Page Special { #fo-first-page} To get a special header on the first page, one possibility is to insert it into the flow instead of the static content. Alternatively, use a page master referring to different page masters for the first page and the rest. Here is a code sample: :::xml First page. Other page. ### Blank Pages { #fo-blank-pages} Sometimes it is desirable to insert blank pages within your output, starting, for example, a new chapter on an odd page or an even page. A blank page can be forced by using `break-before="page-even"` or similar properties, or by a force-page-count="end-on-odd" on a page sequence. To write "This page is intentionally left blank" (or something similar) on an intentionally blank page, first define a conditional page master with a page master specific for blank pages. This allows you to specify static content for blank pages (by definition, a page is blank if no content from a flow is rendered on the page). Omit your normal headers and footers, and use (for example) an extended header to print the "..left blank" statement: :::xml Normal footer Intentionally left blank. ### Floats { #floats} Floats (fo:float) are supported with some limitations: - the "clear" fo:float attribute is ignored; only the float attribute (left or right) is used - overlapping of floats in the Y is not handled (even in the case there would not be overlap in the X direction) - floats that extend beyond the body region are not properly handled and will overflow past the edge of the region - if a float extends to bottom of the body region and there are footnotes in the page the float may overlap with the footnote region - floats next to a table are not supported unless the start and end of the table happens in between the start and end of the float ### Preformatting Content { #fo-preformat} Sometimes it is desirable to retain linebreaks and hard spaces, and to get preformatted text to pass through without being changed. The XSL-FO specification provides some properties for this: [white-space-collapse](http://www.w3.org/TR/xsl11/#white-space-collapse) and [linefeed-treatment](http://www.w3.org/TR/2001/REC-xsl-20011015/slice7.html#white-space-collapse). In FOP, use white-space-collapse="false" on an enclosing block. ### Total Document Pages { #fo-total-pages} It is frequently desirable to know the total number of pages in a document and to use that number within the document. For example, you might wish to show the page number on the first page as being "page 1 of 12". To accomplish this in **XSL 1.0**, place an empty block with an id at the end of the flow: :::xml ... Get the number of the last page as follows: :::xml This does not work in certain situations: multiple page sequences, an initial page number other than 1, or forcing a certain page count, thereby producing blank pages at the end. In **XSL 1.1**, you get another option to do this: make sure an "id" is set on the page-sequence and reference it using fo:page-number-citation-last. First, the page-sequence: :::xml There is no reliable way to get the real total page count with FO mechanisms. You can only get *page numbers*. The FOP library provides a method to get the total page count after an FO document has been rendered. One possibility is to implement your own wrapper to do a dummy rendering, inquire the total page count and then perform the real rendering, passing the total page count to the XSLT processor to splice it into the generated FO. For example: :::java import org.apache.fop.apps.*; import org.xml.sax.*; import java.io.*; import javax.xml.transform.*; import javax.xml.transform.sax.*; import javax.xml.transform.stream.*; class rendtest { private static FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); private static TransformerFactory tFactory = TransformerFactory.newInstance(); public static void main(String args[]) { OutputStream out; try { //Load the stylesheet Templates templates = tFactory.newTemplates( new StreamSource(new File(args[1]))); //First run (to /dev/null) out = new org.apache.commons.io.output.NullOutputStream(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); Transformer transformer = templates.newTransformer(); transformer.setParameter("page-count", "#"); transformer.transform(new StreamSource(new File(args[0])), new SAXResult(fop.getDefaultHandler())); //Get total page count String pageCount = Integer.toString(driver.getResults().getPageCount()); //Second run (the real thing) out = new java.io.FileOutputStream(args[2]); out = new java.io.BufferedOutputStream(out); try { foUserAgent = fopFactory.newFOUserAgent(); fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); transformer = templates.newTransformer(); transformer.setParameter("page-count", pageCount); transformer.transform(new StreamSource(new File(args[0])), new SAXResult(fop.getDefaultHandler())); } finally { out.close(); } } catch (Exception e) { e.printStackTrace(); } } } Declare and use the parameter "page-count" in your XSLT. It is possible to run into a convergence problem with this solution. Replacing the "#" placeholder in the first run with the actual page count in the second run, may change the total number of pages in the document. ### Aligning Regions { #fo-region-align} Although it may seem counterintuitive, the regions on a page may overlap. Defining a certain body region does not automatically constrain other regions. Instead, this has to be done explicitly. Sometimes for creative reasons it may be desirable to have the regions overlap. Otherwise, you will want to set them up so that the header does not overlap body content or the body extend into the footer. Assuming you wish to keep the regions separate, if you have a header region with an extent of 20mm, you should define a margin for the body region of at least 20mm too. Otherwise the header content may overwrite some stuff in the body region. This applies similarly to the extent of the after region and the bottom margin of the body region. ### Drawing Lines { #fo-lines} It is frequently desirable to draw lines in a document, as separators, side bars or folding marks. There are several possibilities: - Horizontal lines can be drawn using [fo:leader](http://www.w3.org/TR/xsl11/#fo_leader). - Use a solid border on a suitable fo:block. This will work for horizontal and vertical lines only. - Insert a graphic. GIF, PNG SVG, whatever. ### Validating XSL-FO { #fo-validate} Here are a couple of methods for validating XSL-FO: * [RenderX](http://www.renderx.com) has provided an [Unofficial DTD for FO Documents](http://www.renderx.com/Tests/validator/fo.dtd.html), which may be helpful in validating general FO issues. * [AntennaHouse](http://www.antennahouse.com) has provided a tool called [focheck](https://github.com/AntennaHouse/focheck) for XSL-FO validation using RELAX NG and Schematron FOP also maintains an [Unofficial FOP Schema](http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/fop/src/foschema/fop.xsd?view=co) in the FOP Subversion Repository. This document can be used either to validate against the FO standard, or against the actual FOP implementation. See the notes near the beginning of the document for instructions on how to use it. ### Producing landscape pages { #landscape} Pages in landscape format can easily be produced by exchanging the page-height and page-width values of a simple-page-master element. ::::xml ### External Resources { #external-resources} Resources needed by an XSL-FO file that are external to it (graphics, for example), are defined in the XSL-FO standard as being of type "uri-specification". This is defined in the standard at [Section 5.11 Property Datatypes](http://www.w3.org/TR/xsl11/#datatype), which includes a link to the URI standard itself. Refer to the XSL-FO and URI standards themselves for more detailed instructions. URIs may be either absolute or relative to a base URI. (See [FOP: Configuration][fopLatest_config] for information on setting the base URI for a FOP session). Here is an example referencing an external-graphic that is relative to the base URI: :::xml Here is an example referencing an external-graphic that is an absolute URI on a local filesystem: :::xml