How do I create easily a PDF from an SVG with jsPDF?

azn0viet picture azn0viet · Apr 28, 2014 · Viewed 37.5k times · Source

I'm trying to create a pdf but I have some SVG pictures. I found information about this problem, but I just have to use JavaScript, that's to say, no jQuery.

I found jsPDF here : https://github.com/MrRio/jsPDF

There is the plugin jspdf.plugin.sillysvgrenderer.js (in the same folder) and where we can find an exemple of PDF created in the folder test.

But when I try to generate the PDF on my own, it doesn't work and I don't understand why.

Do you know how to do it?

Answer

Tima picture Tima · Nov 17, 2014

I got this plugin working, but only with SVG file from the tests and the I saw in the doc that only PATHs are supported :(

There is already the issue on github https://github.com/MrRio/jsPDF/issues/384

If paths are ok for here is my code (it's more or less the code from the tests):

function demoSvgDocument() {
    var doc = new jsPDF();
    var test = $.get('013_sillysvgrenderer.svg', function(svgText){
        var svgAsText = new XMLSerializer().serializeToString(svgText.documentElement);
        doc.addSVG(svgAsText, 20, 20, doc.internal.pageSize.width - 20*2)

        // Save the PDF
        doc.save('TestSVG.pdf');
    });
}       

Another point to consider, you have to run all examples on a server. Otherwise you won't see any results probably because of the security