Save SVG Data To A File Using the svg-export JavaScript library

Save SVG Data To A File Using the svg-export JavaScript library
Save SVG Data To A File Using the svg-export JavaScript library
svg-export is a vanilla JavaScript library that exports and saves SVG data embedded in the document as Image, PDF, or SVG file.

How to use it:

1. Download and load the svg-export.js library in the document.

<script src="svg-export.min.js"></script>

2. Load the Canvg library if you need to export SVG data as an image.

<script src="https://unpkg.com/canvg/lib/umd.js"></script>

3. Load the following JavaScript libraries if you need to export SVG data as a PDF.

<script src="https://cdn.jsdelivr.net/npm/pdfkit/js/pdfkit.min.js"></script>
<script src="https://github.com/devongovett/blob-stream/releases/download/v0.1.3/blob-stream.js"></script>
<script src="https://cdn.jsdelivr.net/npm/svg-to-pdfkit/source.min.js"></script>

4. Export your SVG as an SVG file.

svgExport.downloadSvg(
  // SVG ID
  "#mysvg",
  // Fille name
  "Filename",
  {  custom size
    width: 200, 
    height: 200 
  }
);

5. Export your SVG as an image.

svgExport.downloadPng(
  // SVG ID
  "#mysvg",
  // Fille name
  "Filename",
  {
    // options here
  }
);
svgExport.downloadJpeg(
  // SVG ID
  "#mysvg",
  // Fille name
  "Filename",
  {
    // options here
  }
);

6. Export your SVG as a PDF file.

svgExport.downloadPdf(
  // SVG ID
  "#mysvg",
  // Fille name
  "Filename",
  {
    // options here
  }
);

7. Full options with default values.

{
  originalWidth: 100,
  originalHeight: 100,
  width: 100,
  height: 100, 
  scale: 1,
  useCSS: true,
  excludeByCSSSelector: '', // e.g. [stroke='red'], [stroke='green'], [display='none'], .text-muted.
  transparentBackgroundReplace: "white",
  allowCrossOriginImages: false,
  pdfOptions: {
    customFonts: [],
    pageLayout: { margin: 50, margins: {} },
    addTitleToPage: true,
    chartCaption: "",
    pdfTextFontFamily: "Helvetica",
    pdfTitleFontSize: 20,
    pdfCaptionFontSize: 14
  }
};

8. Execute a callback function after the file export has completed.

{
  onDone: function(){
    // do something
  }
};

Changelog:

v2.0 (10/22/2025)

  • support Typescript, UMD and ESM module + minor fixes

06/23/2023

  • Added onDone()

v1.3.0 (01/08/2023)

  • Added the excludeByCSSSelector option and added notes about optimizing performance for large SVGs.
  • Fixed a bug when min-x and min-y of SVG’s viewBox is not 0.

v1.2.0 (09/12/2021)

  • Includes ability to export svgs containing images

12/28/2020

  • fix issue with array-like CSSStyleDeclaration object

The post Save SVG Data To A File Using the svg-export JavaScript library appeared first on CSS Script.


Discover more from RSS Feeds Cloud

Subscribe to get the latest posts sent to your email.

Discover more from RSS Feeds Cloud

Subscribe now to keep reading and get access to the full archive.

Continue reading