Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Svg to Pdf using jspdf

Tags:

svg

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

like image 503
Priyesh Tiwari Avatar asked Dec 30 '14 14:12

Priyesh Tiwari


3 Answers

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(/\r?\n|\r/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

like image 118
Purushoth Avatar answered Nov 13 '22 13:11

Purushoth


I've tried both svg2pdf.js and addSvgAsImage using canvg internally. Both didn't work well for me, the resulting images in the pdf where either incorrectly positioned or displayed.

I've ended up doing the following which works very well:

  1. convert the SVG to PNG without any libraries, see my answer to "Convert SVG to image (JPEG, PNG, etc.) in the browser".
  2. just add the result to the pdf using the normal addImage method
like image 3
klues Avatar answered Nov 13 '22 12:11

klues


I think the current jspdf version (2.3.1) has an addSvgAsImage method, but it takes the svg as a string. I guess you could use an ajax call to retrieve the SVG content, but I just have the SVG in my code and pass it in that way.

like image 2
cmzmuffin Avatar answered Nov 13 '22 13:11

cmzmuffin