You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用wkhtmltopdf转换含内联SVG页面为PDF的渲染问题求助

问题:wkhtmltopdf 渲染内联SVG到PDF失败的可行方案?

尝试将某Adobe InDesign导出的网页转换为PDF,使用工具版本为:wkhtmltopdf 0.12.6 (with patched qt)。

我使用的自定义打印样式如下:

@media print {
    body > div:nth-child(1) {
        top: -50px !important;
        page-break-after: always;
        -webkit-transform: scale(2) translate(162px,216px) !important;
    }
    body > div:nth-child(2) {
        top: 1630px !important;
        -webkit-transform: scale(2) translate(162px,216px) !important;
    }
}

页面中通过<img>标签引用的SVG文件(本地/远程)都能正常渲染,但内联SVG被完全忽略。我尝试用JavaScript将内联SVG转换为带base64 Data URI的<img>标签,代码如下:

Object.defineProperty(SVGElement.prototype, 'outerHTML', {
    get: function () {
        var $node, $temp;
        $temp = document.createElement('div');
        $node = this.cloneNode(true);
        $temp.appendChild($node);
        return $temp.innerHTML;
    },
    enumerable: false,
    configurable: true
});

var a = new Array(document.getElementsByTagName('svg').length);
for (i=0; i < document.getElementsByTagName('svg').length; i++) { a[i] = document.getElementsByTagName('svg')[i]; }

for (i=0; i < a.length; i++) {
    var b = document.createElement('img');
    b.setAttribute('width', '100%');
    b.setAttribute('height','100%');
    b.setAttribute('src','data:image/svg+xml;base64,' + btoa(a[i].outerHTML.toString()));
    b.setAttribute('type','image/svg+xml');
    a[i].parentNode.insertBefore(b, a[i]);
    a[i].parentNode.removeChild(a[i]);
}

通过CSS给生成的<img>添加红色边框,能确认标签已成功插入,但SVG内容仍无法显示。我试过URL编码、base64编码两种方式,甚至仅包含黑色圆形的极简内联SVG也无法在PDF中渲染。此外还尝试过用iframe引入SVG,以及通过Wayback Machine查找旧版QTweb浏览器但无法运行2013年左右的版本,不确定是否有帮助。

我使用的wkhtmltopdf命令行参数如下:

a=`cat indd.js | tr -d '
'`; \
wkhtmltopdf --page-width 8.5in --page-height 11in \
  -B 0 -L 0 -T 0 -R 0 \
  --user-style-sheet indd.css --print-media-type \
  --run-script "$a" \
  https://indd.adobe.com/content/2/85f1142c-e198-4797-911c-73c0ccdfb874/1735598996323/package/1/publication-7.html \
  test99.pdf

请问有没有可行方案能让该文档正确渲染?

内容的提问来源于stack exchange,提问作者John O

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 11:34:58