问题 使用jspdf将Svg渲染为Pdf


我在使用jspdf将svg元素渲染为pdf时遇到了麻烦。我使用插件 https://github.com/CBiX/svgToPdf.js/ 去做这个。

以下是我的代码

// I recommend to keep the svg visible as a preview
var tmp = document.getElementById("chartContainer");
var svgDoc = tmp.getElementsByTagName("svg")[0];
var pdf = new jsPDF('p', 'pt', 'a4');
svgElementToPdf(svgDoc, pdf, {
scale: 72 / 96, // this is the ratio of px to pt units
removeInvalid: false // this removes elements that could not be translated to pdf from the source        svg
});
pdf.output('datauri'); // use output() to get the jsPDF buffer

它正在生成空白pdf。请帮忙


6344
2017-12-30 14:09


起源

svgToPdf仅支持g,line,rect,ellipse,circle,text元素和一些属性。只需将其作为一个简单的演示。 - cuixiping
@Priyesh Tiwari:我得到同样的问题svg到pdf转换,你是怎么解决问题的? - Noman Akhtar


答案:


你可以使用 canvg

第1步:从DOM获取“SVG”标记代码

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

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

第2步: 使用 canvg 创造 帆布 来自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 Repo: https://github.com/gabelerner/canvg


11
2018-03-04 05:52



你的JSFiddle不适用于Firefox(我试过FF47 Windows) - Basj
任何控制台错误? @Basj - Purushoth
当我点击“获取PDF”@Purushoth时没有任何反应,这是错误 ReferenceError: canvg is not defined。似乎你的jsfiddle中没有正确设置链接: gabelerner.github.io/canvg/canvg.js 不存在。你能更新一下吗?提前致谢! - Basj
外部资源似乎已被移除/移动。但代码将使用正确的外部引用。点击此处了解更多详情,github.com/gabelerner/canvg。 - Purushoth
现在修好了, jsfiddle.net/Purushoth/hvs91vpq @Basj。谢谢你指出。 - Purushoth