vue-mathjax icon indicating copy to clipboard operation
vue-mathjax copied to clipboard

how to export the formula to an image

Open 2010hexi opened this issue 5 years ago • 2 comments

does the vue mathjax provide a method to covert the formula to an image (svg, base64 etc)? if yes, how to use ? any API document to check ?

2010hexi avatar Jul 17 '20 05:07 2010hexi

Have you know how to do it? if yes, you can add a comment under this issue

justforuse avatar Aug 21 '21 12:08 justforuse

I have somewhat figured this out. Using domToImage, it is possible to save the rendered formula into SVG, JPG or PNG:

Using the code-snippet below i was able to select the formula preview and save it as image:

<template>
    <div>
        <v-textarea v-model="formula" no-resize outlined name="formula-input" label="Latex Formula"></v-textarea>

        <vue-mathjax id="putty" :formula="getFormulaInput"></vue-mathjax>

        <v-btn color="primary" class="ma-5" @click="saveAsSVG">
            Save as SVG
       </v-btn>
    </div>
</template>

<style scoped>
a {
    text-decoration: none;
}
</style>

<script>
import { VueMathjax } from 'vue-mathjax'
import domtoimage from 'dom-to-image';

export default {
    name: "TMathjaxViewer",
    components: {
        'vue-mathjax': VueMathjax
    },
    data () {
        return {
            formula: 'x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}'
        }
    },
    computed: {
        getFormulaInput() {
            return '$$' + this.formula + '$$';
        }
    },
    methods: {
        getMathElement() {
            /* 
             * I dont know a better way to do this, but what we try to do here is the following:
             * We want to select the HTML element on the page that contains the rendered formula.
             * Our top-level reference to this element is the 'putty' element. From here we have
             * to select: 'MathJax_Display > MathJax-Element-1-Frame > nobr > MathJax-Span-1'.
             * This selection path is implemented below.
             */
            return document.getElementById("putty").children [1].children [0].children [0].children [0];
        },
        saveAsSVG() { 
            var element = this.getMathElement();

            domtoimage.toSvg(element)
            .then(function (dataUrl) {
                var img = new Image();
                img.src = dataUrl;

                var link = document.createElement("a");

                document.body.appendChild(link); // for Firefox

                link.setAttribute("href", img.src);
                link.setAttribute("download", "formula.svg");
                link.click();
            })
            .catch(function (error) {
                console.error('Something went wrong!', error);
            });
        }
    }
}
</script>

As a fully working example, you can inspect my modified version of mathjax-viewer.

PhilipJonasFranz avatar Jul 30 '22 20:07 PhilipJonasFranz