How to convert SVG files to PDF in JSPDF using javascript

I struggled to convert SVG files to PDF using JSPDF. Here I worked in the following code.

 var doc = new jsPDF();
    var test = $.get('amChart.svg', function(svgText){
    //  console.log(svgText);
        var svgAsText = new XMLSerializer().serializeToString(svgText.documentElement);
        console.log(svgAsText);
        doc.addSVG(svgAsText, 20, 20, doc.internal.pageSize.width - 20*2)
//console.log(doc);
        // Save the PDF
  doc.output('datauri');
    });

I get this script from this SO answer . His results are only blank pdf . When I console.log(doc)before the exit will be the results shown. But this will not result in a PDF ...

And I also work in the SVGELEMENTOPDF function from this GITHUB URL , and I also worked in this code.

// I recommend to keep the svg visible as a preview
var svg = $('#container > svg').get(0);
// you should set the format dynamically, write [width, height] instead of 'a4'
var pdf = new jsPDF('p', 'pt', 'a4');
svgElementToPdf(svg, pdf, {
    scale: 72/96, // this is the ratio of px to pt units
    removeInvalid: true // this removes elements that could not be translated to pdf from the source svg
});
pdf.output('datauri'); // use output() to get the jsPDF buffer

But I can’t achieve this. And kindly advise me ... How to solve this problem in JSPDF

+4
1

, :

  • svgCrowbar SVG

    var uri = svgCrowbar(eGraph);
    
  • SVG PNG dataURI,

    // Create image object which will enable the graph to be saved (via canvas)
    var image = new Image();
    image.onload = function () {
        // Create canvas 
        var canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext('2d');
        context.drawImage(image, 0, 0);
    
        // Save DataURI for later use
        window.sitescriptdata.dataURI[id] = canvas.toDataURL('image/png');
        window.sitescriptdata.numDataURIsLoaded++;        
    
        ...
    
    };
    image.src = uri;
    
  • jsPDF.addImage(), PNG PDF

, SVG PDF . 100% , PDF , , jsPDF, .

+1

Source: https://habr.com/ru/post/1570560/


All Articles