Click here to Skip to main content
Click here to Skip to main content

Enable Your Users to Write Math Equations in Your Web and Desktop Apps

, 30 Jan 2008 GPL3
Rate this:
Please Sign up or sign in to vote.
This article shows you how you can let your users type mathematical equations in popular TeX format and render them as GIF images in your web and desktop applications with just 10 minutes of coding effort.

Introduction

If you own applications such as Blogs, Forums or Wiki and strive to delight your customers with every new release, you probably don't need justification for this feature. In this article, I'll show you how you can allow your users to type in math equations and have them rendered in nice textbook format with absolutely minimal coding effort on your part.

The basic idea is to let the user type in something like this: <img src=".?$ x^2 = 25 $">

The above request first goes to your default.aspx file, where a line of code detects if it's a request for an image and transfers it to a handler. The handler uses MimeTeX to generate the GIF file for the equation and returns to the browser. Fortunately, you don't have to care about any of these, as it's all wrapped and ready for drag and drop.

If you are responsible for any of these types of applications, you owe it to your users to give them this ability:

  • Blogs
  • Forums
  • Wiki
  • Email apps
  • Instant messengers
  • HTML editors
  • Word processing

Essentially, any application that ultimately renders user content in graphical form can add this feature. It doesn't have to be HTML content. For instance, a note-keeping software can detect the TeX content during editing surrounded by $ markers and replace them with a nice graphical form. It can use the exact same library given in this article for this purpose.

Tip:

How to show equations without any coding or even having your own server?

If you don't want to deploy and maintain code in this article, you can use my server for free. You can also use it on ANY blogs, Wikis or websites which do not support TeX and math equations.

To use my server, append http://shitalshah.com by the equation you want. Here's an example:

<img src="http://www.shitalshah.com?$ x^2 = 25 $">

Give it a try!

Background

MimeTeX is the guts of this code. MimeTeX is written by John Forkosh to mainly run under UNIX and as a CGI EXE under Windows. Obviously, while this works, it has many disadvantages like you have to have an ability to run a CGI EXE on IIS, which is a difficult feature for shared IIS hosting. Even if you have a dedicated server, the CGI EXE solution won't scale if you want to support thousands of users. Also, users would be required to add mimetex.exe into the image tag's source, which is less intuitive for users of applications like Blogs or Forums.

For this reason, I decided to convert the MimeTeX code into a Win32 DLL. This is a pretty simple task of taking C files, creating a VC++ Win32 DLL project, adding a DLL export and making other minor changes. But the bigger problem comes later: the DLL runs in-process and hence we should make sure that the C code is free from memory leaks. Unfortunately, this wasn't the case, but fortunately the debug functions like _CrtDumpMemoryLeaks and the VC++ IDE made it a little easier to find them. So, after a weekend's effort, this uncharted UNIX code was free from all known memory leaks. Over the next couple of weeks, John Forkosh and I were exchanging long emails discussing the 10 lines of changes I had made, analyzing them, perfecting them and thoroughly testing the code. It was great fun. The result was the MimeTeX Win32 DLL, which you can now call from your .NET code using DLLImport.

My next step was to create the ASP.NET IHttpHandler that would wrap this call, add caching on top of it and allow other customizations and admin functionality.

Using the Code

You can use this code in three ways:

  • Integrate with your own web apps

    Download the code, add the files in the folder named OnlyRequiredFiles (For VB.NET, look under the VB.NET Version folder) into your ASP.NET project and drop the MimeTex.DLL in the bin folder. Edit your default.aspx page and put this line somewhere in Page_Load or Page_Init (if you are using custom page templates):

    Astrila.Eq2Img.ShowEq.HandleEquationQueries();

    Recompile! Make sure the CachedEqImages folder exists and the ASP.NET user has write permissions for it. That's all there is! You may now create an HTML file in the virtual root folder with an example image tag the same as the one shown at the start of this article for testing.

  • Use as a separate web app

    Copy the Eq2Img folder in your wwwroot. Create a virtual folder, make sure the CachedEqImages folder exists and the ASP.NET user has write permissions for it, and that default.aspx is configured as the default page. You should now be up and running! Remember, your users would need to reference this virtual folder in the image tags like this: <img src="Eq2Img?$ x^2 = 25 $">

  • Use in desktop apps

    This is pretty easy. You just need to DLLImport MimeTex.DLL and call the CreateGifForEq function from your Windows Forms app like this:

        [System.Runtime.InteropServices.DllImport("MimeTex.dll")]
        internal static extern int CreateGifFromEq(string expr, 
                                                 string fileName);

    You can look into a sample Windows Forms app in the Eq2ImgWinForms folder, which looks like this:

The next question might be what is the format of the equations? How do you write Greek symbols, integrals, limits and so on? The format is known as TeX (or LaTeX) and you might be familiar with it if you have ever authored a scientific document in your school years. If not, it's a pretty simple format to learn. For instance, to display the pi symbol you just write \pi and to display the integration sign you write \int and so on. You can find good documentation here and here, but if you choose to be lazy, just use the free WYSWYG equation editor called TeXAide which will build the TeX string for you. Note that TeX ignores white spaces.

Points of Interest

You might have noticed that MimeTeX goes beyond just supporting the equations conforming to TeX format. For instance, you can also create sophisticated figures using LaTeX commands such as the following:

This is really cool because this feature allows your users to author scientific content just with MimeTeX. More examples are at John's website.

I've also thrown in some admin functionality to let you delete cache files (these are very small, typically 1 KB JPG files). You can access this using Eq2ImgAdmin.aspx. This page also lets you dynamically unload the MimeTeX DLL. Remember that this is a pure Win32 DLL, so it gets locked by the ASP.NET process once it gets loaded, unlike managed .NET DLLs. That means you can't update the DLL without restarting the IIS, an unfortunate scenario for shared hosting or even otherwise. To solve this problem, the admin page allows you to dynamically unload this unmanaged DLL from the process on demand. For the technically curious, I simply used GetModuleHandle and FreeLibrary Windows API calls. The admin functionality by default is not enabled. Follow the messages it shows to enable it. Also note that you can exclude this page completely without losing the core functionality.

The code supports a bunch of customization settings that you can put in web.config. By default none are required, but if you prefer, for example, you can choose to run MimeTeX out of the process instead of in-proc or you can run it as CGI or from an external URL. You can set the maximum length of equation strings and maximum cache size and cache folder and so on. I haven't got enough time to document them, but they are easy to figure out from the class Eq2ImgSettings and they all take the form:

<appSettings>
<add key="Eq2Img_ClientCacheAgeInSeconds" value="200" />
</appSettings>

Finally, here's the security disclosure you all have been waiting for: you are running unmanaged code from ASP.NET when you call into the MimeTeX DLL. That means ASP.NET should have sufficient permission for this (by default it does). However, the bigger concern is the possible nasty C bugs such as memory leaks and invalid pointers that might make your website unstable. In my testing, it does work satisfactorily; the in-proc mode is very scalable and MimeTeX itself has been in use on many websites since 2002. However, if you ever notice a problem, you do have an exit strategy of setting an option in your web.config file so that MimeTeX will run out of process or even completely disable it and serve only the cached files. As MimeTeX is an open source project, anyone has the liberty to fix the bugs as soon as they are found.

Need Help?

I'm passionate about enabling the web to allow users to author scientific content. If you have any problems using this code in your application, you can contact me for free assistance.

History

  • 23rd August, 2005 - Newly created.
  • 24th August, 2005 - Fixed a concurrency bug, created VB.NET version of the code.
  • 30th January, 2008 - Article content updated

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

Share

About the Author

sytelus
Web Developer
United States United States
Shital Shah is a Software Engineer and is passionate about physics, mathematics and learning algorithms. You can reach him through his website and blog.

Comments and Discussions

 
QuestionCan i use this in Unity3d? PinmemberRaducuMihai18-Jul-14 5:57 
QuestionBadImageFormatException PinmemberMeysam Tolouee18-Apr-14 22:08 
AnswerRe: BadImageFormatException PinmemberMember 92618733-Sep-14 3:25 
QuestionMy vote of 5 Pinprofessionalabbaspirmoradi7-Sep-13 2:05 
QuestionIs it possible to changed the background color of the image created? Pinmembernepai8717-Aug-13 19:50 
Questionvshost32.exe/vshost32-clr2.exe has stopped working PinmemberIvan160115-Jul-13 21:46 
QuestionGetting erro in web application PinmemberDarshit Pandya5-Aug-12 23:30 
GeneralMy vote of 5 Pinmembermanoj kumar choubey14-Mar-12 4:47 
GeneralMy vote of 5 PinmemberMd. Rashidul Hasan Masum30-Sep-11 22:27 
GeneralMath Equations in Your Web and Desktop Apps Pinmembertaniasiemence5-Jan-11 1:08 
Questionreturn value CreateGifFromEq PinmemberJarekżźćvbnm21-Sep-10 10:16 
GeneralCalling Convention VS 2010 "PInvoke Error" Pinmemberjacob.hales4-Aug-10 23:42 
GeneralRe: Calling Convention VS 2010 "PInvoke Error" PinmemberGagnon Claude5-Aug-10 16:32 
GeneralRe: Calling Convention VS 2010 "PInvoke Error" PinmemberJarekżźćvbnm21-Sep-10 9:59 
GeneralRe: Calling Convention VS 2010 "PInvoke Error" [modified] Pinmembersahar j10-Jan-12 21:07 
GeneralCompiling the DLL and the lib static library PinmemberGagnon Claude4-Aug-10 9:28 
GeneralMy vote of 5 Pinmemberj03x228-Jul-10 7:02 
QuestionHi PinmemberMember 264603717-Sep-09 23:46 
GeneralI got it working but had to put MimeTex.DLL in System32 folder of Windows Pinmembergery1283-Sep-09 2:20 
GeneralHope to Use It On Production System Pinmemberrajaquila4-Aug-09 16:47 
GeneralAwesome work! Pinmemberpanuvin8-Jun-09 2:21 
Question64-bit Version? Pinmemberabrockwell19-May-09 10:34 
AnswerRe: 64-bit Version? Pinmemberhairpin869-Jun-12 13:14 
GeneralRe: 64-bit Version? PinmemberMina W Alphonce9-Aug-14 23:56 
GeneralDoes not work in asp.net application Pinmemberxsoftdev9-Jan-09 14:06 
GeneralRe: Does not work in asp.net application Pinmemberwuxbar2219-Apr-09 1:10 
GeneralRe: Does not work in asp.net application Pinmembergery1283-Sep-09 2:32 
GeneralSimple Pinmemberalhimikyr28-Dec-08 1:47 
QuestionAlgorithm Pinmembersubscribe000130-Sep-08 9:38 
GeneralAwesome Pinmemberjosemaocu22-Aug-08 4:01 
GeneralGeneral PinmemberJorge Bay Gondra22-Aug-08 3:31 
QuestionAnti-Aliasing? White text on black background? Pinmemberpanurge13-Feb-08 11:36 
GeneralRe: Anti-Aliasing? White text on black background? Pinmemberpanurge13-Feb-08 11:39 
QuestionRe: Anti-Aliasing? White text on black background? Pinmemberpanurge14-Feb-08 4:26 
AnswerRe: Anti-Aliasing? White text on black background? Pinmemberyunke24-Jul-11 22:13 
GeneralGreat thanks PinmemberCorsar12-Nov-07 3:01 
GeneralPNG Pinmembernbastos22-Oct-07 23:07 
QuestionHow to declare MimTeX.dll in Visual Basic 6? Pinmemberigorpett3-Oct-07 5:22 
AnswerRe: How to declare MimTeX.dll in Visual Basic 6? PinmemberQuoc San4-Sep-08 18:31 
QuestionHow to use it in Vc 6.0? Pinmemberphilophos16-Sep-07 7:22 
GeneralGreat work! Pinmembercontrolstudy25-Apr-07 3:00 
GeneralThe source is kinda wrong PinmemberXH_expanders26-Nov-06 16:27 
QuestionCreate Image to stream? PinmemberDallmeier29-Aug-06 22:38 
GeneralVisual Studio 2005 Pinmemberffolch26-Jun-06 7:33 
QuestionScalable? Pinmemberelziko9-Feb-06 1:19 
QuestionMimeTex on Wintel -- BadBlue and MS Access Pinmemberahffahff5-Dec-05 2:40 
AnswerRe: MimeTex on Wintel -- BadBlue and MS Access PinmemberJohn Forkosh14-Dec-05 23:04 
GeneralExcellent PinmemberBrian Delahunty21-Sep-05 12:14 
GeneralDownload The Latest Updates From The Author's Website Pinmembersytelus20-Sep-05 12:45 
QuestionLaTex PinmemberSoonerFan9-Sep-05 3:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141030.1 | Last Updated 30 Jan 2008
Article Copyright 2005 by sytelus
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid