Im Trying to save page as png using html2canvas, but svg is not coming. I have literally tried so many things over the internet but somehow i m getting issues in everything
Following is the code: (its basically the sample project thats get genearted on npx create-react-app)
package.json
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"canvg": "^4.0.1",
"html2canvas": "^1.4.1",
"jspdf": "^2.5.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"svg2pdf.js": "^2.2.1",
"web-vitals": "^2.1.4"
},
App.js
import logo from './logo.svg';
import './App.css';
import html2canvas from "html2canvas";
function exportMethod() {
var container = document.getElementById('root'); // full page
html2canvas(container, {
windowWidth: window.innerWidth * 0.9,
windowHeight: window.innerHeight * 1.5,
allowTaint: true,
onclone: function (document) { //todo }
ignoreElements: function (element) { //add if needed }
}).then(function (canvas) {
var link = document.createElement("a");
document.body.appendChild(link);
link.download = `test.jpg`;
link.href = canvas.toDataURL();
link.target = '_blank';
link.click();
});
}
function App() {
return (
<div className="App">
<button onClick={exportMethod}>Export </button>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.............................
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
<object data={logo} type="image/svg+xml">
<img src=`https://filesamples.com/samples/image/svg/sample_640%C3%97426.svg` />
</object>
</div>
);
}
export default App;
Above is the result , if i run the project.
but if click on export button the image thats get downloaded looks like following:
Things i have tried:
var svg = document.getElementsByTagName('object');
console.log("***********************", svg[0].contentWindow)
var xml = new XMLSerializer().serializeToString(svg[0].contentWindow.document);
var svg64 = btoa(xml); //for utf8: btoa(unescape(encodeURIComponent(xml)))
var b64start = 'data:image/svg+xml;base64,';
var image64 = b64start + svg64;
return image64;
svgElements.forEach(function (item) {
item.setAttribute("width", item.getBoundingClientRect().width);
item.setAttribute("height", item.getBoundingClientRect().height);
item.style.width = null;
item.style.height = null;
});
many other things which i found but dont know why it is not working.
codesandbox link
https://codesandbox.io/s/condescending-banzai-irbinl?file=/src/App.js


