fast-reflexes / better-react-mathjax

MIT License
124 stars 16 forks source link

Accessing the mathjax tex2svg function #26

Closed lukaskesch closed 2 years ago

lukaskesch commented 2 years ago

First of all let me say that your package is awesome!

For my project i need to convert tex to a svg image. Using the example code for accessing the mathjax object did not work for me. Here is the code:

const mjContext = useContext(MathJaxBaseContext); 
    if (mjContext) 
         mjContext.promise.then((mathJaxObject) => {
            const tex = "\\dfrac{5}{3}";
            let svg = mathJaxObject.tex2svg(tex, { em: 50 });
        });

It would be greatly appreciated if you could help me with this.

fast-reflexes commented 2 years ago

Hi!

Thanks for writing! Remember to star this library if you like it :)

What you're trying to do requires you to load another Mathjax source file, e.g. you should change the source from the default tex-chtml.js to text-svg.js:

        <MathJaxContext
            src={"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"} // if you use CDN
        >
            ...
        </MathJaxContext>

With this Mathjax file, it will automatically load the tex input component and svg output component which then makes sure that the function you want to use exists on the MathJax object.

So this input file automatically loads something equal to (in the Mathjax config, should you for some reason want to add it explicltly as well):

        loader: { load: ["input/tex", "output/svg"] }

Remember though that these components can only be used when you ALSO include a Mathjax source file option which actually contains these components.

You can read about the different source file options here: https://docs.mathjax.org/en/latest/web/components/combined.html#combined-components-1

... and here you can read about the options to the conversion function: https://docs.mathjax.org/en/latest/web/typeset.html#conversion-options-1

The options seem a bit odd (I don't know how it affects the output knowing what the surrounding text is like... looks from my sandbox that the output just adapts to the size of the surrounding text). But the display option affects the output at least :)

Also, I chose in the sandbox to run the commands inside a call to mathJax.startup.promise, this is just to ensure that it is done after initial typesetting of the page, which may or may not be desirable. It should work in most cses without that too.

Here is a sandbox: https://codesandbox.io/s/better-react-mathjax-26-5ij771

Good luck!

lukaskesch commented 2 years ago

Thanks for the quick feedback!

The code from the sandbox link works perfectly for my purpose. I needed the svg image file for further processing. Thanks alot! I really appreciate the your quick and helpful response.