jsPDF Tutorial to Export SVG Image to PDF Document Using canvg Library in Browser Using Javascript Full Project For Beginners

 

 

index.html

 

 

<!-- Source of svg -->
<div id="svg-container">
   <svg height="500" version="1.1" width="500" xmlns="http://www.w3.org/2000/svg" style="overflow: hidden; position: relative;"><desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Created with Raphaël 2.1.0</desc><defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></defs><text x="50" y="50" text-anchor="middle" font="10px "Arial"" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: middle; font: 10px Arial;" stroke-width="0.1155822959137042" transform="matrix(8.6436,-0.3768,0.3768,8.6436,-311.9625,-338.3442)"><tspan dy="3.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">TEST</tspan></text><path fill="none" stroke="#000000" d="M138.9921875,75L282.5237926136365,68.7428977272727" stroke-dasharray="4,3" opacity="0.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); opacity: 0.5;"></path><circle cx="282.5237926136365" cy="68.7428977272727" r="5" fill="#ffffff" stroke="#000000" class="handle arm axis-x" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></circle><path fill="none" stroke="#000000" d="M138.9921875,75L141.6863771024465,136.80198776758414" stroke-dasharray="4,3" opacity="0.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); opacity: 0.5;"></path><circle cx="141.6863771024465" cy="136.80198776758414" r="5" fill="#ffffff" stroke="#000000" class="handle arm axis-y" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></circle><circle cx="138.9921875" cy="75" r="5" fill="#ffffff" stroke="#000000" class="handle center" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></circle></svg>
</div>

<div>
  <button id="getPdf">Generate PDF</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvg/1.5/canvg.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>

 

 

script.js

 

 

//Add event listener
document.getElementById("getPdf").addEventListener("click", getPdf);

function getPdf() {
  //Get svg markup as string
  var svg = document.getElementById('svg-container').innerHTML;

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

  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');


  context.clearRect(0, 0, canvas.width, canvas.height);
  canvg(canvas, svg);

  var imgData = canvas.toDataURL('image/png');

  // Generate PDF
  var doc = new jsPDF('p', 'pt', 'a4');
  doc.addImage(imgData, 'PNG', 0, 0, 500, 500);
  doc.save('test.pdf');

}

Leave a Reply