C# tool to render latex in Winforms or PNG/BMP/etc?
The following might help you. Feel free to edit my code to accommodate all known best practices.
Step 0
Make sure you have installed LaTeX distro (either TeX Live or MikTeX) and ImageMagick. Register the ImageMagick's path to the System Path such that convert
command is available everywhere.
Step 1
Create a new WinForm project in C# (or VB). Drag one RichTextBox
, one Button
and one PictureBox
onto the Form
. Write the code behind as follows.
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
namespace LaTeXEditor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
File.WriteAllText("input.tex", richTextBox1.Text);
Process p1 = new Process();
p1.StartInfo.FileName = "batch.bat";
p1.StartInfo.Arguments = "input";
p1.StartInfo.UseShellExecute = false;
p1.Start();
p1.WaitForExit();
pictureBox1.ImageLocation = "output.png";
}
private void Form1_Load(object sender, EventArgs e)
{
richTextBox1.Text =
@"\documentclass[preview,border=12pt]{standalone}
\usepackage{amsmath}
\usepackage{tikz}
\begin{document}
PSTricks is more powerful than this one\\ \tikz\draw[red] (0,0) circle (1);
\end{document}
";
}
}
}
Step 2
Add a new file named batch.bat
to the project. The hard-coded literals should be avoided if necessary by defining additional parameters to the batch file.
rem batch.bat
rem %1 represents the file name with no extension.
pdflatex -jobname=output %1
convert -density 200 -alpha on output.pdf output.png
Modify the post build event as follows to copy the batch.bat
to the project output directory.
Step 3
Compile and make a try as follows.
use this code!!!
const string latex = @"\frac{2+2}{2}";
const string fileName = @"formula.png";
File.Open(fileName, FileMode.OpenOrCreate).Close();
var parser = new WpfMath.TexFormulaParser();
var formula = parser.Parse(latex);
var renderer = formula.GetRenderer(WpfMath.TexStyle.Display, 20.0, "Arial");
var bitmapSource = renderer.RenderToBitmap(0, 0);
var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmapSource));
using (var target = new FileStream(fileName, FileMode.Create))
{
encoder.Save(target);
}
pictureBox2.Image = Image.FromFile(fileName);