我需要使用xml文件渲染PDF。由于某些原因,PDF引擎不能很好地使用按百分比指定宽度的表。
这是源html
<table class="table">
<thead>
<tr>
<td style="width:60%;">foo</td>
<td style="width:40%;">bla</td>
</tr>
</thead>
<tbody>
<tr>
<td>foo</td>
<td>bla</td>
</tr>
</tbody>
</table>
使用现有的xslt它将转换为xml 1:
<fo:table>
<fo:table-header>
<fo:table-row>
<fo:table-cell width="60%">
fool
</fo:table-cell>
<fo:table-cell width="40%">
bla
</fo:table-cell>
</fo:table-row>
</fo:table-header>
<fo:table-body>
<fo:table-row>
<fo:table-cell>
foo
</fo:table-cell>
<fo:table-cell>
bla
</fo:table-cell>
</fo:table-row>
</fo:table-body>
</fo:table>
使用上述xml的PDF表将不会被划分为60%40%。
但是,以下是可以的
xml 2
<fo:table>
<fo:table-column column-width="60%"/>
<fo:table-column column-width="40%"/>
<fo:table-header>
<fo:table-row>
<fo:table-cell width="60%">
foo
</fo:table-cell>
<fo:table-cell width="40%">
bla
</fo:table-cell>
</fo:table-row>
</fo:table-header>
<fo:table-body>
<fo:table-row>
<fo:table-cell
foo
</fo:table-cell>
<fo:table-cell>
bla
</fo:table-cell>
</fo:table-row>
</fo:table-body>
</fo:table>
所以问题是,给定源html,如何使用xslt使用相应的<fo:table-column>
值在<fo:table>
元素下方添加<fo:table-cell width=
元素?理想情况下,如果xml 1具有多个<fo:table-column>
,则不应有重复的<fo:table-row>
。
我只需要添加额外的<fo:table-column>
,因为正在进行其他转换。
我看过类似的问题,但仍然没有解决方案Adding element in middle of xml using xslt
我当前的方法:
<xsl:template match="html:table">
<xsl:copy>
<xsl:for-each select=".//html:tr[html:td/@style][1]/html:td">
<xsl:if test="contains(@style,'width')">
<fo:table-column>
<xsl:attribute name="column-width">
<xsl:value-of select="substring-after(substring-before(@style, ';'),'width:')"/>
</xsl:attribute>
</fo:table-column>
</xsl:if>
</xsl:for-each>
</xsl:copy>
</xsl:template>
这不起作用,因为未将<fo:table-column>
添加到原始<fo-table
的下面,而是创建了一个新的<fo-table>
,并在其中添加了<fo:table-column>
这将使用一些宽度数据获取您的第一张表行,并将其用于输出。
<xsl:template match="@* | *">
<xsl:copy>
<xsl:apply-templates select="@* | * | text()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="fo:table">
<xsl:copy>
<xsl:for-each select=".//fo:table-row[fo:table-cell/@width][1]/fo:table-cell">
<fo:table-column>
<xsl:attribute name="column-width" select="@width"/>
</fo:table-column>
</xsl:for-each>
<xsl:apply-templates select="@* | *"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>