通过TCPDF使用子svg图像转换SVG

时间:2016-06-05 15:31:34

标签: image svg tcpdf

我试图用tcpdf将svg转换为pdf。我正在使用

$pdf->ImageSVG(
    $file=$my_source,...

Everyt工作正常,直到在$ my_source中插入了另一个svg图像,如:

<image xlink:href='subSvg.svg'/>

但我总是通过tcpdf收到错误消息。有没有人体验过svg在tcpdf中插入sub-svg图像?

更新

我再试一次:这只是一个警告。生成PDF。 Tcdpf只能释放sub svg的ressource:警告:xml_parser_free():19不是第22913行的tcpdf.php中的有效XML Parser资源

这是一个示例subSvg.svg

<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
width="300" height="300" 
viewBox="0 0 300 300"
preserveAspectRatio="xMinYMin meet">
<desc>123456</desc>
<g id="elements" fill="black" stroke="none">
<rect x="0" y="0" width="30" height="30" />
</g>
</svg> 

是否可以引用svg内联(data:image / svg + xml; utf8,)?

<image xlink:href='@<svg ...'/>

1 个答案:

答案 0 :(得分:0)

您可以考虑预处理SVG图像,内联引用的SVG。这是使用XSLT 2.0的可能方法草案:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:svg="http://www.w3.org/2000/svg"
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  version="2.0">

  <xsl:template match="node()|@*">
    <xsl:param name="attributes"/>

    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:copy-of select="$attributes"/>
      <xsl:apply-templates select="node()"/>
    </xsl:copy>
  </xsl:template>


  <xsl:template match="svg:image[matches(@xlink:href, '\.svg$')]">
    <xsl:variable name="imageUrl">
      <xsl:choose>
        <xsl:when test="contains(@xlink:href, '//')">
          <xsl:value-of select="@xlink:href"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="concat(replace(base-uri(), '/[^/]+$', '/'), @xlink:href)"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:variable>

    <xsl:variable name="imageDocument" select="document($imageUrl)"/>

    <xsl:if test="not($imageDocument)">
      <xsl:message terminate="yes">
        <xsl:value-of select="concat('Could not find image ', $imageUrl)"/>
      </xsl:message>
    </xsl:if>

    <xsl:apply-templates select="$imageDocument">
      <xsl:with-param name="attributes" select="(@x, @y, @width, @height, @transform)"/>
    </xsl:apply-templates>
  </xsl:template>
</xsl:stylesheet>

确保

  • 您正在使用XSLT 2.0处理器(对于PHP上下文中的XSLT 2.0,请参阅this post),
  • XSLT处理器可以在xlink:href属性中的URL下访问引用的SVG,
  • SVG不会递归地互相引用,
  • 外部SVG不使用CSS和样式属性,这将导致内部SVG的不期望的重新样式,
  • 内联不会导致ID冲突,例如打破<use>元素或过滤器。

根据SVG文件的外观,XSLT可能需要改进,例如:重写ID和ID引用以解决最后一点。