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

Angular中如何将SVG内容导出至PDF文件?

如何用jsPDF将SVG添加到PDF中

你当前代码的问题在于错误地将SVG数据以JPEG格式传入addImage方法,jsPDF的addImage不支持直接解析SVG内容为JPEG,导致SVG无法渲染到PDF里。下面是两种可行的解决方法:

方法1:通过Canvas转换SVG为图片

先把SVG渲染到Canvas,再将Canvas转为图片数据传入jsPDF:

// 1. 创建SVG的Blob对象和URL
const svgContent = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /></svg>';
const svgBlob = new Blob([svgContent], { type: 'image/svg+xml' });
const svgUrl = URL.createObjectURL(svgBlob);

// 2. 创建图片元素加载SVG
const img = new Image();
img.onload = function() {
  // 3. 创建Canvas并绘制SVG内容
  const canvas = document.createElement('canvas');
  canvas.width = img.width;
  canvas.height = img.height;
  const ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0);

  // 4. 将Canvas转为图片数据并添加到PDF
  const doc = new jsPDF();
  doc.addImage(canvas.toDataURL('image/png'), 'PNG', 10, 20, 20, 20);
  doc.save('pdf-with-svg.pdf');

  // 清理临时URL
  URL.revokeObjectURL(svgUrl);
};
img.src = svgUrl;

方法2:使用jsPDF的SVG插件

如果项目允许引入插件,可以用jspdf-plugin-svg直接添加SVG,能更好保留矢量特性:

import jsPDF from 'jspdf';
import 'jspdf-plugin-svg';

const svgContent = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /></svg>';
const doc = new jsPDF();

// 直接调用addSVG方法添加SVG
doc.addSVG(svgContent, 10, 20, 20, 20);
doc.save('pdf-with-svg.pdf');

注意事项

  • 方法1依赖浏览器Canvas API,适合纯前端环境;
  • 方法2需确保已正确安装并引入对应插件,渲染质量更优。

内容的提问来源于stack exchange,提问作者Asra Fatima

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 03:22:39