且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jspdf将Svg渲染为PDF

更新时间:2023-02-12 22:07:43

您可以使用 canvg 来做到这一点.

You can do that using canvg.

第一步:从DOM获取"SVG"标记代码

Step1: Get "SVG" markup code from DOM

var svg = document.getElementById('svg-container').innerHTML;

  if (svg)
    svg = svg.replace(/\r?\n|\r/g, '').trim();

第2步: 使用 canvg 从svg创建 canvas .

Step 2: Use canvg to create canvas from svg.

  var canvas = document.createElement('canvas');
  canvg(canvas, svg);

第3步: 使用.toDataURL()

  var imgData = canvas.toDataURL('image/png');
  // Generate PDF
  var doc = new jsPDF('p', 'pt', 'a4');
  doc.addImage(imgData, 'PNG', 40, 40, 75, 75);
  doc.save('test.pdf');

在此处查看演示 http://jsfiddle.net/Purushoth/hvs91vpq/193/

Canvg回购: https://github.com/gabelerner/canvg