Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

Render Svg to Pdf using jspdf

I am having trouble in rendering svg element to pdf using jspdf . Iam using plugin https://github.com/CBiX/svgToPdf.js/ to do this.

Below is my code

// 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

It is generarting blank pdf. Please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do that using canvg.

Step1: Get "SVG" markup code from DOM

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

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

Step 2: Use canvg to create canvas from svg.

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

Step 3: Create image from canvas using .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');

Check the demo here http://jsfiddle.net/Purushoth/hvs91vpq/193/

Canvg Repo: https://github.com/gabelerner/canvg


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...