Javascript Project to Export SVG DOM Element to SVG,PNG Image and PDF Document in Browser Full Project For Beginners

 

 

 

index.html

 

 

<div class="container">
  <svg id='iamsvg' width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
	<rect fill="red" x="25" y="25" width="50" height="50">
</svg>
</div>
<div class="container">
  <button id="svg">🟥 as svg</button>
  <button id="png">🟥 as png</button>
  <button id="pdf">🟥 as pdf</button>
</div>

 

 

style.css

 

 

* {
  box-sizing: border-box;
}

html,
body {
  height: 100vh;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
}

.emoji {
  font-size: 2rem;
}

 

 

script.js

 

 

import * as saveSvgAsPng from "https://cdn.skypack.dev/save-svg-as-png@1.4.17";
import { jsPDF } from "https://cdn.skypack.dev/jspdf@2.3.1";

const svgBtn = document.getElementById("svg");
const pngBtn = document.getElementById("png");
const pdfBtn = document.getElementById("pdf");

svgBtn.addEventListener("click", () => {
  const element = document.getElementById("iamsvg");
  const filename = "myfilename.svg";
  saveSvgAsPng.saveSvg(element, filename);
});

pngBtn.addEventListener("click", () => {
  const element = document.getElementById("iamsvg");
  const filename = "myfilename.png";
  saveSvgAsPng.saveSvgAsPng(element, filename);
});

pdfBtn.addEventListener("click", () => {
  const element = document.getElementById("iamsvg");
  const filename = "myfilename.pdf";

  saveSvgAsPng.svgAsPngUri(element).then((dataUrl) => {
    console.log(dataUrl)
    const doc = new jsPDF();
    doc.addImage(dataUrl, "PNG", 0, 0).save(filename);
  });
});

Leave a Reply