How to Render LaTeX to PNG in C#

In this step by step how-to guide, you’ll learn how to render LaTeX to PNG in C#. The code snippet in this tutorial makes it easy to render latex to png in C# in a few steps.

Steps to Render LaTeX to PNG in C#

  1. Install Aspose.TeX for .NET package from NuGet.org
  2. Include Aspose.TeX, Aspose.TeX.IO, and Aspose.TeX.Presentation.Image namespaces
  3. Apply license to Aspose.TeX for .NET using SetLicense method
  4. Create TeXOptions object with TeXConfig settings
  5. Set input and output working directory to read and save files
  6. Set TerminalOutput option to OutputFileTerminal
  7. Create PngSaveOptions object and set properties
  8. Create ImageDevice object to be passed to Typeset method
  9. Run typesetting operation using Typesetting method

The above steps will help convert TeX to PNG in C# easily. The input TeX file will be read from the working directory specified in the options and the output PNG files will be placed in the output working directory.

Code to Render LaTeX to PNG in C#

using System;
using System.IO;
//Add reference to Aspose.TeX for .NET API
//Use following namespaces to render Latex file to PNG format
using Aspose.TeX;
using Aspose.TeX.IO;
using Aspose.TeX.Presentation.Image;
namespace RenderLatexToPNG
{
class Program
{
static void Main(string[] args)
{
//Set Aspose license before rendering latex file to PNG format
Aspose.TeX.License AsposeTeXLicense = new Aspose.TeX.License();
AsposeTeXLicense.SetLicense(@"c:\asposelicense\license.lic");
//Create TeXOptions object with ObjectTex config settings
TeXOptions TeXFormatOptions = TeXOptions.ConsoleAppOptions(TeXConfig.ObjectTeX());
//Set input and output working directory
TeXFormatOptions.InputWorkingDirectory = new InputFileSystemDirectory(@"c:\samples");
TeXFormatOptions.OutputWorkingDirectory = new OutputFileSystemDirectory(@"c:\samples");
//Set output terminal option to file terminal to save to a file
TeXFormatOptions.TerminalOut = new OutputFileTerminal(TeXFormatOptions.OutputWorkingDirectory);
//PNG save options
PngSaveOptions pngSaveOptions = new PngSaveOptions();
pngSaveOptions.Resolution = 300;
TeXFormatOptions.SaveOptions = pngSaveOptions;
//Create an ImageDevice object
ImageDevice imageDevice = new ImageDevice();
//Run typesetting.
TeX.Typeset("customtex", imageDevice, TeXFormatOptions);
}
}
}

The code snippet shown above makes it clear how to render TeX to PNG in C# in a few steps. As we’re saving the output to the file system, so instead of console output terminal, we have specified file terminal as our output terminal.

Using this tutorial, you can easily build your own LaTeX renderer for C# and .NET applications.

 English