how to export svg form web page in js

https://stackoverflow.com/questions/2483919/how-to-save-svg-canvas-to-local-filesystem

1. server return


2. base64 encode

// This example was created using Protovis & jQuery
// Base64 provided by http://www.webtoolkit.info/javascript-base64.html
// Modern web browsers have a builtin function to this as well 'btoa'
function encode_as_img_and_link(){
// Add some critical information
$("svg").attr({ version: '1.1' , xmlns:"http://www.w3.org/2000/svg"}); var svg = $("#chart-canvas").html();
var b64 = Base64.encode(svg); // or use btoa if supported // Works in recent Webkit(Chrome)
$("body").append($("<img src='data:image/svg+xml;base64,\n"+b64+"' alt='file.svg'/>")); // Works in Firefox 3.6 and Webit and possibly any browser which supports the data-uri
$("body").append($("<a href-lang='image/svg+xml' href='data:image/svg+xml;base64,\n"+b64+"' title='file.svg'>Download</a>"));
}

base64 bug

中文 bug ???


// Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.


const getToday = (symbol = `-`) => {
const date = new Date();
const dd = String(date.getDate()).padStart(2, '0');
// Month January is 0!
const mm = String(date.getMonth() + 1).padStart(2, '0');
const yyyy = date.getFullYear();
// format
const today = `${yyyy}${symbol}${mm}${symbol}${dd}`;
// const today = mm + '/' + dd + '/' + yyyy;
return today;
} const getTodayTimestamp = (symbol = `-`) => {
const date = new Date();
const dd = String(date.getDate()).padStart(2, '0');
// Month January is 0!
const mm = String(date.getMonth() + 1).padStart(2, '0');
const yyyy = date.getFullYear();
const timestamp = date.getTime();
// format
const todayTimestamp = `${yyyy}${symbol}${mm}${symbol}${dd}${symbol}${timestamp}`;
return todayTimestamp;
} const svgBase64StringConvert = () => {
const body = document.querySelector(`body`);
// svg uuid
const svg = document.querySelector(`svg`);
const html = svg.parentElement.innerHTML;
// let html = svg.parentNode.innerHTML;
// let html = svg.innerHTML();
// html = `
// <svg width="100%" height="100%" viewBox="0 0 1000 1000">
// ${html}
// </svg>
// `;
const base64String = btoa(html);
const date = new Date();
const time = date.getFullYear() + date.getMonth() + 1 + date.getDate();
const timestamp = new Date().getTime();
// const timestamp = getTodayTimestamp();
const img = `
<img
src="data:image/svg+xml;base64, ${base64String}"
alt="live-map-${timestamp}.svg"
download="live-map-${timestamp}.svg"
/>
`;
const alink = `
<a
href="data:image/svg+xml;base64, ${base64String}"
alt="live-map-${timestamp}.svg"
download="live-map-${timestamp}.svg"
data-class="visibility: none;"
/>
`;
body.insertAdjacentHTML(alink);
alink.click();
// remove alink
} const svgToBase64String = () => {
const body = document.querySelector(`body`);
// svg uuid
const svg = document.querySelector(`svg`);
const html = svg.parentElement.innerHTML;
const base64String = btoa(html);
const date = new Date();
const time = date.getFullYear() + date.getMonth() + 1 + date.getDate();
const timestamp = new Date().getTime();
const alink = `
<a
href="data:image/svg+xml;base64, ${base64String}"
alt="live-map-${timestamp}.svg"
download="live-map-${timestamp}.svg"
data-class="visibility: none;"
/>
`;
body.insertAdjacentHTML(`beforeend`, alink);
alink.click();
// remove alink
}

https://stackoverflow.com/questions/23218174/how-do-i-save-export-an-svg-file-after-creating-an-svg-with-d3-js-ie-safari-an/23218877

3. XMLSerializer & serializeToString


//get svg element.
var svg = document.getElementById("svg"); //get svg source.
var serializer = new XMLSerializer();
var source = serializer.serializeToString(svg); //add name spaces.
if(!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){
source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
}
if(!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)){
source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
} //add xml declaration
source = '<?xml version="1.0" standalone="no"?>\r\n' + source; //convert svg source to URI data scheme.
var url = "data:image/svg+xml;charset=utf-8,"+encodeURIComponent(source); //set url value to a element's href attribute.
document.getElementById("link").href = url;
//you can download svg file by right click menu.

solution

svg.outerHTML & svg.parentElement.innerHTML


const getTodayTimestamp = (symbol = `-`) => {
const date = new Date();
const dd = String(date.getDate()).padStart(2, '0');
// Month January is 0!
const mm = String(date.getMonth() + 1).padStart(2, '0');
const yyyy = date.getFullYear();
const timestamp = date.getTime();
// format
const todayTimestamp = `${yyyy}${symbol}${mm}${symbol}${dd}${symbol}${timestamp}`;
return todayTimestamp;
} const autoSVGDownload = (uuid = ``) =>{
const timestamp = getTodayTimestamp();
const filename = `SVG 现场图-${timestamp}.svg`;
// const filename = `live-map-${timestamp}.svg`;
// uuid
const svg = document.querySelector(`svg`);
// const html = svg.parentElement.innerHTML;
const html = svg.outerHTML;
// xml namespace, support browser open preview
const xml = `<?xml version="1.0" encoding="UTF-8"?>\n${html}`;
const element = document.createElement('a');
element.setAttribute('href', 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(xml));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
} export {
getTodayTimestamp,
autoSVGDownload,
}; export default autoSVGDownload;

how to export svg form web page in js的更多相关文章

  1. VML/SVG在Web开发中一些常见的框架

    1.借鉴自: http://www.codefans.net/soft/3061.shtml 来源于网上. flowchart.js  http://adrai.github.io/flowchart ...

  2. [Project] Simulate HTTP Post Request to obtain data from Web Page by using Python Scrapy Framework

    1. Background Though it's always difficult to give child a perfect name, parent never give up trying ...

  3. Snap.svg – 现代 Web 开发必备的 JavaScript SVG 库

    SVG 是一种很好的 Web 技术方案,可以用来创建互动,在任何大小的屏幕上都会很好看.与分辨率无关的矢量图形.而这里推荐的 Snap.svg 这个 JavaScript 可以让你像 jQuery 操 ...

  4. 解读Web Page Diagnostics网页细分图

    解读Web Page Diagnostics网页细分图 http://blog.sina.com.cn/s/blog_62b8fc330100red5.html Web Page Diagnostic ...

  5. 网页细分图结果分析(Web Page Diagnostics)

    Discuz开源论坛网页细分图结果分析(Web Page Diagnostics) 续LR实战之Discuz开源论坛项目,之前一直是创建虚拟用户脚本(Virtual User Generator)和场 ...

  6. Atitit.web三大编程模型 Web Page Web Forms 和 MVC

    Atitit.web三大编程模型 Web Page    Web Forms 和 MVC 1. 编程模型是 Web Forms 和 MVC (Model, View, Controller). 2.  ...

  7. [转]Calling Web Service Functions Asynchronously from a Web Page 异步调用WebServices

    本文转自:http://www.codeproject.com/Articles/70441/Calling-Web-Service-Functions-Asynchronously-from Ove ...

  8. Tutorial: Importing and analyzing data from a Web Page using Power BI Desktop

    In this tutorial, you will learn how to import a table of data from a Web page and create a report t ...

  9. Android WebView常见问题的解决方案总结----例如Web page not available

    之前android虚拟机一直都可以直接联网,今天写了一个WebView之后,突然报出了Web page not available的错误,但是查看虚拟机自带的浏览器,是可以上网的,所以检查还是代码的问 ...

随机推荐

  1. 分布式缓存 — memcache

    MemCache是一个自由.源码开放.高性能.分布式的分布式内存对象缓存系统,用于动态Web应用以减轻数据库的负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高了网站访问的速度.Mem ...

  2. 最简单直接地理解Java软件设计原则之单一职责原则

    理论性知识 定义 单一职责原则, Single responsibility principle (SRP): 一个类,接口,方法只负责一项职责: 不要存在多余一个导致类变更的原因: 优点 降低类的复 ...

  3. Spring Boot 基础,理论,简介

    Spring Boot 基础,理论,简介 1.SpringBoot自动装配 1.1 Spring装配方式 1.2 Spring @Enable 模块驱动 1.3 Spring 条件装配 2.自动装配正 ...

  4. Java——变量类型

    Java变量类型: 在Java中,所有的变量在使用前必须声明.格式: type identifier [ = value ][, identifier [ =value]-.]; type为Java数 ...

  5. springsecurity教程一

    可以看这个人的springsecurity省的自己写了 1.springsecurity学习目标 2.1 springsecurity简介 2.2 springsecurity快速入门demo 1): ...

  6. Linux lsblk和df命令区别

    lsblk 查看的是block device,也就是逻辑磁盘大小. df查看的是file system, 也就是文件系统层的磁盘大小

  7. 2020 CCPC Wannafly Winter Camp Day1 C. 染色图

    2020 CCPC Wannafly Winter Camp Day1 C. 染色图 定义一张无向图 G=⟨V,E⟩ 是 k 可染色的当且仅当存在函数 f:V↦{1,2,⋯,k} 满足对于 G 中的任 ...

  8. hdu 6268 Master of Subgraph(点分治+bitset)

    You are given a tree with n nodes. The weight of the i-th node is wi. Given a positive integer m, no ...

  9. uva10891 Game of Sum(博弈+区间dp+优化)

    题目:点击打开链接 题意:两个人做游戏,共有n个数,每个人可以任选一端取任意多连续的数,问两个人都想拿最多的情况下,先手最多比后手多拿多少分数. 思路:这题一开始想到的是用dp[i][j]表示区间[i ...

  10. java——API

    API定义: 可以网上下载一个jdk_api文档用来查找一些函数. 匿名对象的创建  匿名对象做为返回值和参数实例: Random的使用: