From 77ed4a3b57f071cc45bff5c74573c2a74eefdb9d Mon Sep 17 00:00:00 2001 From: Christian Swinehart Date: Thu, 19 Oct 2023 16:37:32 -0400 Subject: [PATCH] :tada: (fonts) use Playfair & Lato in exported PNGs --- .../grapher/src/modal/DownloadModal.tsx | 28 +++++++++++++++++-- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/packages/@ourworldindata/grapher/src/modal/DownloadModal.tsx b/packages/@ourworldindata/grapher/src/modal/DownloadModal.tsx index 7092b70ab58..4956196fe03 100644 --- a/packages/@ourworldindata/grapher/src/modal/DownloadModal.tsx +++ b/packages/@ourworldindata/grapher/src/modal/DownloadModal.tsx @@ -84,6 +84,7 @@ export class DownloadModal extends React.Component { return this.props.manager } + @observable private svgContent?: string @observable private svgBlob?: Blob @observable private svgPreviewUrl?: string @@ -94,17 +95,38 @@ export class DownloadModal extends React.Component { @action.bound private export(): void { this.createSvg() + const reader = new FileReader() reader.onload = (ev: any): void => { this.svgPreviewUrl = ev.target.result as string this.tryCreatePng(this.svgPreviewUrl) } - reader.readAsDataURL(this.svgBlob as Blob) + + // merge the embedded font data into the svg before rendering to png + fetch("/fonts/embedded.css") + .then((data) => data.text()) + .then((css) => { + const svgWithFonts = this.svgContent?.replace( + /(]*?>)/, + `$1` + ) + if (svgWithFonts) + reader.readAsDataURL( + new Blob([svgWithFonts], { + type: "image/svg+xml;charset=utf-8", + }) + ) + else throw new Error() + }) + .catch(() => { + // fall back to the font-free version if something goes wrong + reader.readAsDataURL(this.svgBlob as Blob) + }) } @action.bound private createSvg(): void { - const staticSVG = this.manager.staticSVG - this.svgBlob = new Blob([staticSVG], { + this.svgContent = this.manager.staticSVG + this.svgBlob = new Blob([this.svgContent], { type: "image/svg+xml;charset=utf-8", }) }