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

svg2pdf.js与jsPDF版本迁移后svg()调用及保存失败问题

解决方案:解决svg2pdf.js 2.2.2 + jsPDF 2.5.1 中 e.multiply is not a function 错误

可能的原因及修复步骤

1. 替换SVG DOM元素为SVG字符串传递

错误提示中的multiply方法缺失,大概率是直接传入SVG DOM元素时,svg2pdf无法正确处理其矩阵变换相关对象。尝试将SVG序列化为字符串后再传入:

import { jsPDF } from "jspdf";
import 'svg2pdf.js'

// 确保downloadPdf是async函数
async function downloadPdf() {
  const pdf = new jsPDF('p', 'mm', [width, height]);

  const blankSvgElement = document.querySelector('#svg-pdf-headFoot').contentDocument.querySelector('svg');
  // 将SVG DOM序列化为字符串
  const svgString = new XMLSerializer().serializeToString(blankSvgElement);

  await pdf.svg(svgString, { x: 0, y: 0, width: 100, height: 200 });

  pdf.save(filename);
}

2. 调整jsPDF版本至兼容范围

虽然官方标注svg2pdf.js 2.x兼容jsPDF 2.3+,但部分版本组合存在隐性兼容性问题,尝试降级jsPDF至2.3.1:

npm install jspdf@2.3.1
# 或 yarn add jspdf@2.3.1

3. 检查SVG内容的合法性

确保你的SVG中没有复杂或非标准的变换属性,比如自定义矩阵变换语法,svg2pdf对部分SVG特性的支持存在局限。可先使用极简SVG测试功能是否正常:

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

4. 规避React中直接操作DOM的潜在问题

在React项目中,直接使用document.querySelector可能获取到未完全挂载的DOM元素,建议结合useRef和useEffect确保SVG已加载完成:

import { useRef, useEffect } from 'react';
import { jsPDF } from "jspdf";
import 'svg2pdf.js'

function PdfComponent() {
  const svgContainerRef = useRef(null);

  async function downloadPdf() {
    if (!svgContainerRef.current) return;
    const blankSvgElement = svgContainerRef.current.contentDocument.querySelector('svg');
    const svgString = new XMLSerializer().serializeToString(blankSvgElement);
    
    const pdf = new jsPDF('p', 'mm', [100, 200]);
    await pdf.svg(svgString, { x: 0, y: 0, width: 100, height: 200 });
    pdf.save('test.pdf');
  }

  return (
    <div>
      <object ref={svgContainerRef} id="svg-pdf-headFoot" data="/path/to/your/svg.svg" type="image/svg+xml" />
      <button onClick={downloadPdf}>下载PDF</button>
    </div>
  );
}

内容的提问来源于stack exchange,提问作者Seid Saydahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:59:51