jsPDF

by Shang-De You

HTML

<script src="https://unpkg.com/[email protected]/dist/html2canvas.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.2.0/polyfills.umd.js"></script>
<div>
  <button id="exportPDF">
    Export PDF
  </button>
</div>
<div>
<svg id="print" xmlns="http://www.w3.org/2000/svg" version="1.1" width="920px" height="1696px" ><g class="bp__force-directed-chart__g" transform="translate(0, 0) scale(1)"><defs><marker class="bp__force-directed-chart__arrow-marker" viewBox="0 -5 10 10" markerWidth="10" markerHeight="10" orient="auto" id="arrowGov" refX="40" refY="0" style="fill: #f5dab1"><path d="M0,-5L10,0L0,5"></path></marker><marker class="bp__force-directed-chart__arrow-marker" viewBox="0 -5 10 10" markerWidth="10" markerHeight="10" orient="auto" id="arrowForeign" refX="40" refY="0" style="fill: #5EC5D7"><path d="M0,-5L10,0L0,5"></path></marker><marker class="bp__force-directed-chart__arrow-marker" viewBox="0 -5 10 10" markerWidth="10" markerHeight="10" orient="auto" id="arrowPerson" refX="40" refY="0" style="fill: #C2E7B0"><path d="M0,-5L10,0L0,5"></path></marker><marker class="bp__force-directed-chart__arrow-marker" viewBox="0 -5 10 10" markerWidth="10" markerHeight="10" orient="auto" id="arrowCompany" refX="40" refY="0" style="fill: #D099EB"><path d="M0,-5L10,0L0,5"></path></marker><marker class="bp__force-directed-chart__arrow-marker" viewBox="0 -5 10 10" markerWidth="10" markerHeight="10" orient="auto" id="arrowClosed" refX="40" refY="0" style="fill: #909399"><path d="M0,-5L10,0L0,5"></path></marker><marker class="bp__force-directed-chart__arrow-marker" viewBox="0 -5 10 10" markerWidth="10" markerHeight="10" orient="auto" id="arrowLocked" refX="40" refY="0" style="fill: #1778F5"><path d="M0,-5L10,0L0,5"></path></marker></defs><g><path class="link" marker-end="url(#arrowGov)" style="stroke: rgb(245, 218, 177); stroke-width: 2px; fill: none; opacity: 1;" d="M508.54144214296747,625.0634866591143 L668.376916697307,453.13525357692725"></path><path...

JavaScript

document.getElementById('exportPDF').addEventListener('click', function() {

  const { jsPDF } = jspdf
  var doc = new jsPDF();
  html2canvas(document.getElementById('print'), {
    onrendered: function(canvas) {
    	console.log(canvas.width, canvas.height)
      /* var image = canvas.toDataURL("image/png") */
      var image = canvas.toDataURL('image/jpeg', 1.0)
      doc.addImage(image, 'JPEG', 0, 0, canvas.width, canvas.height);
      doc.save('test.pdf');
    }
  });
});