Render Svg to Pdf using jspdf

后端 未结 2 933
栀梦
栀梦 2020-12-01 18:28

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

         


        
相关标签:
2条回答
  • 2020-12-01 18:57

    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

    0 讨论(0)
  • 2020-12-01 19:12

    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
    0 讨论(0)
提交回复
热议问题