Created
December 29, 2020 12:28
-
-
Save bojidaryovchev/3df4c9b1903335b55a9de0920864e3e9 to your computer and use it in GitHub Desktop.
export html elements to an image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// in index.html | |
// <script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js" integrity="sha512-01CJ9/g7e8cUmY0DFTMcUw/ikS799FHiOkA0eyHsUWfOetgbx/t6oV4otQ5zXKQyIrQjGTHSmRVPIgrgLccZi/WMA==" crossorigin="anonymous"></script> | |
// <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js" integrity="sha512-Qlv6VSKh1lgDKGoJbnyA5RMXYcvnpIqhO++MhkIM2fStMcGT9i2T//tSwYFlcyoRRDcDZ+TYHpH8azBBCyqhpSeqw==" crossorigin="anonymous"></script> | |
// in typescript | |
import 'dom-to-image'; | |
import 'file-saver'; | |
import * as mergeBase64 from 'merge-base64'; | |
import { from, forkJoin } from 'rxjs'; | |
import { switchMap, map } from 'rxjs/operators'; | |
declare global { | |
interface Window { | |
saveAs(blob: Blob, fileName: string): Promise<void>; | |
} | |
} | |
declare var domtoimage: { | |
toBlob: (element: HTMLElement) => Promise<Blob>; | |
toPng: (element: HTMLElement) => Promise<string>; | |
}; | |
const b64toBlob = (base64: string) => { | |
return fetch(base64).then((res) => res.blob()); | |
}; | |
// in my case I have to combine 2 separate elements to form an image | |
onExport(): void { | |
forkJoin([ | |
from(htmlElementA), | |
from(htmlElementB), | |
]) | |
.pipe( | |
map((base64) => { | |
return base64.map((s) => s.replace('data:image/png;base64,', '')); | |
}), | |
switchMap((base64: string[]) => { | |
return from( | |
mergeBase64(base64, { direction: true, color: 'ffffff' }) | |
); | |
}), | |
switchMap((base64: string) => from(b64toBlob(base64))) | |
) | |
.subscribe((blob: Blob) => { | |
window.saveAs(blob, 'test.png'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment