Preserving whitespace in PDF after XSL transform

dangerisgo picture dangerisgo · Apr 25, 2012 · Viewed 12.4k times · Source

I'm converting an XML to PDF using XSL transformation. Unfortunately, it is not preserving the whitespace from the XML. For example:

I want to convert this:

Test Line Data         : 0xAA

to PDF from an XML. It looks fine in the XML, it has the 9 spaces between Data and : but in the PDF it shows

Test Line Data : 0xAA

Here is what I currently do. After writing the data to the XML, I will perform the following:

XPathDocument xPathDocDiag = new XPathDocument(this.FileNameDiagXml);
XslCompiledTransform xslTransDiag = new XslCompiledTransform();
XmlTextWriter xmlWriterDiag = new XmlTextWriter(outputFO, System.Text.Encoding.UTF8);
xslTransDiag.Transform(xPathDocDiag, null, xmlWriterDiag);
xmlWriterDiag.Flush();
xmlWriterDiag.Close();

And then launch Apache FOP to convert the FO to PDF. Like I said, unfortunately, the white space is not preserved when I need it to be. I have tried manually adding   in place of spaces in the XML (find and replace) which does work after the conversion, but as we all know, the literal & can't be in XML so that option is out. I have tried using XmlReader and then using

<xsl:preserve-space elements="*"/>

but again, that doesn't work either (no error or anything, just doesn't work).
The section of XSL looks like so:

<xsl:when test="Data != ''">
                <fo:table-cell text-align="left">
                    <fo:block />
                </fo:table-cell>
                <fo:table-cell text-align="left" number-columns-spanned="7">
                    <fo:block font-family="Courier New, Courier, monospace" font-size="9pt"><xsl:value-of select="Data" /></fo:block>
                </fo:table-cell>
            </xsl:when>

I have tried all sorts of attribute modifying to no avail. Am I missing something obvious here?

Answer

Daniel Haley picture Daniel Haley · Apr 25, 2012

Add the attribute white-space="pre" to whatever fo:block you want to preserve the white-space in.

Example:

<fo:block white-space="pre">Test Line Data         : 0xAA</fo:block>

The attribute white-space-treatment="preserve" should also work, but when I tried it in FOP, it didn't.

The attribute white-space-collapse="false" also worked.