xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

export SVG image form web page in js All In One

export SVG image form web page in js All In One

how to export SVG image 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;



refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(455)  评论(6编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-02-14 血液检测 & 创业骗局
点击右上角即可分享
微信分享提示