[Tex/LaTex] Using pdflatex.exe to Convert TeX to PDF within a C#

compilingerrors

I have my TeX file (only firstExample.tex inside my folder) document and I want to convert it to PDF and display it within the application.

\documentclass[11pt]{article}
\begin{document}
this is only a test
$$(x+1)$$
\end{document}

i do this:

 string filename = @"C:\inetpub\wwwroot\MyApp\Application\Temp\firstExample.tex";
                Process p1 = new Process();
                p1.StartInfo.FileName = @"C:\Program Files\MiKTeX 2.9\miktex\bin\x64\pdflatex.exe";
                p1.StartInfo.Arguments = filename;
                p1.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                p1.StartInfo.RedirectStandardOutput = true;
                p1.StartInfo.UseShellExecute = false;

                p1.Start();
                var output = p1.StandardOutput.ReadToEnd();
                p1.WaitForExit();

but output returns :

"This is pdfTeX, Version 3.1415926-2.4-1.40.13 (MiKTeX 2.9 64-bit)
entering extended mode !
I can't write on file `firstExample.log'
Please type another transcript file name: "

instead of the expected PDF

Best Answer

This answer has been tested and it works as expected.

Step 1: Create a batch file

To avoid recompiling the C# source code to be in sync with the (La)TeX compiler you want to use, it will be convenient to create a batch file. The batch file executes (La)TeX compiler behind the scene. Save the batch file anywhere and set the PATH system variable to the batch location. But for the sake of simplicity, you can save it in a directory in which the LaTeX input file exists.

The simplest batch may be as follows

rem batch.bat
rem %1 represents the file name with no extension.
pdflatex -shell-escape %1

Step 2: Create the C# code and compile

The simplest example is as follows:

   using System.Diagnostics;
   class MyApp
    {
        public static void Main(string[] args)
        {
            Process p1 = new Process();
            p1.StartInfo.FileName = "batch.bat";
            p1.StartInfo.Arguments = args[0];
            p1.StartInfo.UseShellExecute = false;

            p1.Start();
            p1.WaitForExit();
         }
     }

Compile it with C# compiler to get MyApp.exe for example. Save it in a specific directory and set PATH system variable to point it. But for the sake of simplicity, you can save it a directory in which the LaTeX input file exists.

Step 3: Create a test LaTeX input file

Create and save the following LaTeX input file in a directory that has read and write permission.

% test.tex
\documentclass[preview,border=12pt,12pt]{standalone}
\begin{document}
Hello World
\end{document}

Step 4: Make a try

MyApp.exe needs a single argument which is the TeX input file name with no extension.

From command prompt, you execute MyApp.exe test.

Step 5: Vote this answer up!

Related Question