A Javascript library to export svg charts from the DOM and download them as an SVG file, PDF, or raster image (JPEG, PNG) format. Can be done all in client-side.

Overview

svg-exportJS Codacy Badge

An easy-to-use client-side Javascript library to export SVG graphics from web pages and download them as an SVG file, PDF, or raster image (JPEG, PNG) format. Written in plain vanilla javascript. Originally created to export D3.js charts.

This library features:

  • Exporting SVG DOM Element objects or serialized SVG string to SVG file, PNG, JPEG, PDF
  • Setting custom size for exported image or graphic
  • High resolution raster image, using scale
  • Including external CSS styles in SVG
  • Exporting text in custom embedded fonts
  • Handling transparent background for JPEG format conversion
  • Exporting SVGs that are hidden on the DOM (display: none, SVGs in hidden modals, dropdowns or tabs, etc.)
  • Exporting SVGs containing images (<image> tag)

Demo available here.

Getting Started

Prerequisites

  • Any of the following browsers: Chrome 38.0+, Edge 18.0+, Firefox 20.0+, Safari 10.1+, Opera 25+
  • Canvg (if you need JPEG/PNG export)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/canvg/3.0.7/umd.min.js"></script>
  • PDFKit, blob-stream and SVG-to-PDFKit (if you need PDF export).
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/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/[email protected]/source.min.js"></script>

Please note that the CDNs above may not be the most up-to-date. The latest source code can be found directly from the github projects, also linked above.

Installation

Either download the plugin and save it in your project, or use script-tags in your html files using the hosted url.

  • Download the plugin svg-export.min.js from this repo, and add it to your project.
  • Add the plugin using the file hosted on Github Pages. Place the script within the <head> tag in your html files (place prerequisites first):
    <!-- svg-exportJS prerequisite: canvg -->
    <script src="https://unpkg.com/[email protected]/lib/umd.js"></script>
    <!-- svg-exportJS plugin -->
    <script src="https://sharonchoong.github.io/svg-exportJS/svg-export.min.js"></script>

Usage

Given the <svg> element:

<svg id="mysvg">...</svg>

In Javascript:

svgExport.downloadSvg(
  document.getElementById("mysvg"), // SVG DOM Element object to be exported. Alternatively, a string of the serialized SVG can be passed
  "chart title name", // chart title: file name of exported image
  { width: 200, height: 200 } // options (optional, please see below for a list of option properties)
);
svgExport.downloadPng("<svg id=\"mysvg\"></svg>", "chart title name", {
  width: 200,
  height: 200,
});
svgExport.downloadJpeg(svgElementObject, "chart title name");
svgExport.downloadPdf(svgString, "chart title name");

See index.html for an example of how to use.

Options

  • width (number) : the width of the resulting image exported, in pixels. Default is the SVG's width on the DOM
  • height (number) : the height of the resulting image exported, in pixels. Default is the SVG's height on the DOM
  • scale (number) : a multiple by which the SVG can be increased or decreased in size. For PNG and JPEG exports, if width, height and scale are not specified, scale is set to 10 for a 10x enlargement to ensure that a higher resolution image is produced. Otherwise, the default scale is 1
  • useCSS (bool): if SVG styles are specified in stylesheet externally rather than inline, setting true will add references to such styles from the styles computed by the browser. If useCSS is false, currentColor will be changed to black. This setting only applies if the SVG is passed as a DOM Element object, not as a string. Default is true
  • transparentBackgroundReplace (string): the color to be used to replace a transparent background in JPEG format export. Default is white
  • allowCrossOriginImages (bool): If the SVG contains images, this option permits the use of images from foreign origins. Defaults to false. Please read Images within SVG below for more detail.
  • pdfOptions
    • pageLayout (object): e.g. { margin: 50, layout: "landscape" }. This is provided to PDFKit's addPage. When the options width and height are not specified, a minimum size of 300x300 is used for the PDF page size; otherwise the page size wraps around the SVG size. Please see the PDFKit documentation for more info
    • addTitleToPage (bool): Default is true
    • chartCaption (string) caption to appear at the bottom of the chart in the PDF. Default is no caption
    • pdfTextFontFamily (string): Font family of title and caption (if applicable) in PDF. See here for a list of available fonts. Default is Helvetica
    • pdfTitleFontSize (number): Default is 20
    • pdfCaptionFontSize (number): Default is 14
    • customFonts (array of objects): Optional argument for custom fonts. e.g. [{ fontName: 'FakeFont', url: 'fonts/FakeFont.ttf'}]. Each object must have two properties: fontName for the font name that appears in the CSS/SVG, and url for the URL of the custom font file to be used in the PDF. A third property styleName specifying the style name to be used can be specified for multi-collection font files (.ttc and .dfont files)

Custom fonts

Regarding embedded custom fonts used in the SVG element (using @font-face for example), please note that for SVG export, custom fonts only show correctly if the system opening the SVG file has the font installed. If this is not possible, please consider using one of the other file formats available.

Images within SVG

This library supports exporting SVGs that contain images in an <image> tag. If you need to export such SVGs to raster images or PDFs, please make sure that you have the latest version of Canvg and SVG-to-PDFKit. If the images' href are external, the allowCrossOriginImages option must be set to true, and the image servers must be configured with the 'Access-Control-Allow-Origin' CORS policy.

Colors

Colors tested to work on all exported formats include CSS color names, HEX, RGB, RGBA and HSL.

SVG graphics in Office documents

Need to add SVG graphics to Office Word, Excel or Powerpoint presentations? SVG files can be inserted as a picture for non-pixelated graphics in Office 2016 or later, including Office 365.

Roadmap

  • Set up package.json and publish to npm (jsdom for Node?)

Not Supported

Since foreignObject does not contain SVG, it is not supported.

Contributing

Contributions are very welcome! Feel free to flag issues or pull requests.

License

Licensed under MIT. See LICENSE for more information.

Contact

Sharon Choong - https://sharonchoong.github.io/

Send me your cheers with a cup of coffee! Ko-Fi

Comments
  • Cannot open SVG in Adobe Illustrator: This SVG is invalid. Validate before Opening

    Cannot open SVG in Adobe Illustrator: This SVG is invalid. Validate before Opening

    Hello, I tried to export an SVG container from my website. The file is downloaded, but I cannot open it in Adobe Illustrator. I get the error This SVG is invalid. Validate before Opening. What might be the reason? The PNG export works fine.

    Thanks!

    Daniel

    opened by dringel 1
  • Not working for SVG Pattern

    Not working for SVG Pattern

    First of all, its wonderful app... But, Its not working while exporting a PDF, When we use a SVG pattern example this pattern:

    <svg id="mysvg" xmlns="http://www.w3.org/2000/svg" width="595.28" height="841.89"> <pattern width="40" height="40" patternUnits="userSpaceOnUse" id="a" viewBox="0 -40 40 40" overflow="visible"> <path fill="none" d="M0 0h40v-40H0z"/> <path fill="#1D0E82" d="M0-40v20h20v-20zM20-20V0h20v-20z"/> </pattern> <g fill="#1D0E82"> <path d="M457-99h20v20h-20zM477-79h20v20h-20z"/> </g> <path fill="url(#a)" d="M0 0h595.28v841.89H0z"/> </svg>

    Any help will be appreciated.. Thanks

    opened by keshavnaidu 1
  • svg export removed foreignObject, How can fix that ?

    svg export removed foreignObject, How can fix that ?

    <svg id="mysvg" height="400" width="100%"> <g class="rects"> <rect x="300" y="40" width="40" height="40" fill="black" stroke="black"></rect> <rect x="50" y="100" width="500" height="200" fill="orange" stroke="gray" opacity="0.5"></rect> </g> <g class="circles"> <circle cx="100" cy="100" r="100" fill="green" stroke="yellow" opacity="0.2"></circle> <circle cx="200" cy="100" r="50" fill="#778899" stroke="blue" opacity="0.5"></circle> <circle cx="400" cy="200" r="150" fill="transparent" stroke="currentColor" opacity="0.8"></circle> </g> <text x="200" y="200" style="font-family: 'Segan', Arial;" font-size="20">Testing 123</text> <foreignObject x="100" y="25" width="160" height="160"> <div> <br><br>GEEKSFORGEEKS<br><br> </div> </foreignObject> </svg>

    wontfix 
    opened by meganathan-codenatives 1
  • Unexpected use of undefined.

    Unexpected use of undefined.

    Codacy detected an issue:

    Message: Unexpected use of undefined.

    Occurred on:

    • Commit: 416f4a13e968c5ca77dfdada35355eaa79568d48
    • File: svg-export.js
    • LineNum: 155
    • Code: if (asString === undefined) { asString = true; }

    Currently on:

    • Commit: 416f4a13e968c5ca77dfdada35355eaa79568d48
    • File: svg-export.js
    • LineNum: 155
    opened by sharonchoong 1
  • Add css filtering options

    Add css filtering options

    Adds an option to filter out some elements from the exported SVG, based on CSS properties. An example is provided in the index.html file, and the README has been updated to document its use.

    I'm open to feedback if some parts need to be modified before being integrated.

    opened by VRaveneau 1
Releases(v1.2.0)
Owner
Hello there! Casually developing stuff for my own use.
null
A generative engine that takes various png layers on a sprite sheet format, combines them and then converts them into a .gif file

Welcome to the Generative GIF Engine v2.0.4 ?? [8 minute read] This python and node app generates layered-based gifs to create NFT gif art! It is fast

Jalagar 112 Jan 2, 2023
A generative engine that takes various png layers on a sprite sheet format, combines them and then converts them into a .gif file

Welcome to the Generative Animated Engine v3.0.1 ?? [8 minute read] This repo used to be called jalagar/Generative_Gif_Engine but because it now suppo

Jalagar 47 May 24, 2022
To-do list" is an app that helps to organize your day. the user simply lists the things that needs to done and the app allows the to mark them as complete when they are done. Made with webpack, JavaScript ES6 , HTML 5 and CSS 3.

Todo-list project This is a Microverse project that entails a to-do-list. Built With HTML CSS Javascript Webpack VS code Live Demo (if available) Live

Youta Lactio Christabelle 10 Aug 3, 2022
Landscape Generator is An open Source web application that generates landscape drawings randomly, then gives you the ability to edit it and export it as SVG or PNG.

Landscape Generator ## About Landscape Generator is An open Source web application that generates landscape drawings randomly, then gives you the abil

null 9 Apr 15, 2022
I'm trying to create simple program for adding the digital signature to a pdf file with self-signed certificate. I use node-signpdf and pdf-lib library.

pdf-digital-signature-with-node-signpdf-ejs I'm trying to create simple program for adding the digital signature to a pdf file with self-signed certif

null 5 Dec 25, 2022
A Javascript library that discourages and prevents image theft/download by preventing client ability to retrieve the image.

ProtectImage.js ProtectImage.js is a Javascript library that helps prevent image theft by disabling traditional user interactions to download/copy ima

null 4 Aug 18, 2022
Grayce Muthui 8 Jun 16, 2022
A simple to do list webpage where you can log the daily tasks you have to do, mark them as checked, modify them, reorder them and remove them. Made using HTML, CSS and JavaScript.

To-Do-List This Webpage is for an app called To-Do-List which helps you add, remove or check tasks you have to do. It is a simple web page which conta

Zeeshan Haider 9 Mar 12, 2022
A web app designed to keep track of activities that are done and those that are and not done. Users can add, delete, mark as completed and update the activities. Built with Javscript, html, css and webpack.e your activites

ToDoListApp A web app designed to help web keep track of activities that are done and those that are still pending. Users can add, delete, mark as com

Francis Wayungi 6 Dec 23, 2022
generate a map server side and save/return it as png image

NFT map generator Request a new map to be generated with latitude and longitude params, for example http://localhost:3000/maps?lat=45.3579&lng=9.4427

Mattia Asti 3 Jul 12, 2022
When pasting screenshots into obsidian notes, convert the images to jpeg and compress them

obsidian-paste-png-to-jpeg This plugin is inspired by obsidian-paste-image-rename, obsidian-paste-image-rename can be used when inserting images renam

null 19 Nov 15, 2022
An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

Snyk Labs 57 Dec 28, 2022
To-Do list a web app for tracking personal progress through the day. Users can input a list of tasks and mark them as completed once they are done. Built with JavaScript and Webpack

To-do-List-Project To Do List Project Description. This project creates a simple HTML list of To Do tasks. It was built using webpack and served by a

Olawale Olapetan 7 Jul 8, 2022
optimize image & upload file to cloud as image bed with tiny image automic.

Rush! 图片压缩 & 直传图床工具 这是一个兴趣使然的项目, 希望 Rush! 能让这个世界的网络资源浪费减少一点点 下载 Downloads 获取最新发行版 功能 Features 拖拽批量压缩图片, 支持格式 jpg/png/gif Drop to optimize, jpg/png/gif

{ Chao } 3 Nov 12, 2022
A little JavaScript plugin to generate PDF, XLS, CSV and DOC from JavaScript Object or DOM element only from the frontend!

?? JavaScript Object to csv, xls, pdf, doc and DOM to html generator ?? A little JavaScript plugin to generate PDF, XLS, CSV and DOC from JavaScript O

null 61 Jan 7, 2023
Export your HTML table to Excel format.

excelExport Export your HTML tables to Excel format. Doc Installation Simply import JQuery & excel-export into your HTML. <script src="https://code.jq

Zenoo 1 Apr 22, 2021
This is a Webpack based to-do-list project. With this app, users can add thier daily routine tasks to the list, mark them as complet, edit them or delete them.

To Do List This is a Webpack based to-do-list project. With this app, users can add thier daily routine tasks to the list, mark them as complet, edit

Ali Aqa Atayee 12 Oct 30, 2022
Aron 8 Dec 17, 2022
Fast and minimal JS server-side writer and client-side manager.

unihead Fast and minimal JS <head> server-side writer and client-side manager. Nearly every SSR framework out there relies on server-side components t

Jonas Galvez 24 Sep 4, 2022