Latex转换之PDF

近期一直在做如何使用latex将模板转换成PDF.现在写下在项目中如何实现。

1.首先你先进官网下载http://www.miktex.org/download。我用的是如下图所示。

在下载好的MikTeX找到如下目录(E:Software)MiKTeX 2.9miktexinx64中的miktex-xetex.

2.自己新建一个模板.tex文件和一个.bat文件。其中在.bat文件中写入miktex-2.9.4813miktexinmiktex-xetex.exe -undump=xelatex test.tex(这是你自己所写的模板文件)

下面是我自己项目中的一个模板,我的.tex文件如下

%!Tex Program = xelatex
documentclass[a4paper]{article}
usepackage{xltxtra}
setmainfont[Mapping=tex-text]{Microsoft YaHei}
egin{document}pagestyle{empty}
section{Unicode support}

subsection{English}
All human beings are born free and equal in dignity and rights.

subsection{Íslenska}
Hver maður er borinn frjáls og jafn öðrum að virðingu og réttindum.

subsection{Русский}
Все люди рождаются свободными
и равными в своем достоинстве и
правах.

subsection{Tiếng Việt}
Tất cả mọi người sinh ra đều được tự do và bình đẳng về nhân phẩm và
quyền lợi.

subsection{简体中文}
你好!!!!!
subsection{繁體中文}
每個人生來平等,享有相同的地位和權利。

subsection{日本語}
すべての人間は自由であり、かつ、尊厳と権利とについて平等である。

section{Legacy syntax}
When he goes---``Hello World!''\
She replies—“Hello dear!”

section{Ligatures}
fontspec[Ligatures={Common, Historical}]{Times New Roman Italic}
fontsize{12pt}{18pt}selectfont Questo è strano assai!

section{Numerals}
fontspec[Numbers={OldStyle}]{Times New Roman}Old style: 1234567\
fontspec[Numbers={Lining}]{Times New Roman}Lining: 1234567

end{document}

3.双击.bat文件进行运行,运行结果如下。

其中调用xetex.cmd口令程序代码如下。

 public static bool GenLatexPdf(string exeFile, string texString, string outPath, out string pdfUrl, out string error)
        {
            pdfUrl = null;
            error = null;

            if (string.IsNullOrWhiteSpace(exeFile) || !File.Exists(exeFile)) // Exe file is not exist
            {
                error = string.Format("Miktex file is not exist: {0}", exeFile);
                LogMethod.WriteLog(LogMethod.LogType.Error, error);
                return false;
            }
            if (string.IsNullOrWhiteSpace(texString)) // Tex string is empty
            {
                error = "Tex string is empty.";
                LogMethod.WriteLog(LogMethod.LogType.Error, error);
                return false;
            }
            if (string.IsNullOrWhiteSpace(outPath)) // Output path is empty
            {
                error = "Output path is empty.";
                LogMethod.WriteLog(LogMethod.LogType.Error, error);
                return false;
            }

            var now = DateTime.Now;
            outPath = string.Format(OutputPathFormat, outPath.TrimEnd('\'), now);
            if (!Directory.Exists(outPath))
            {
                 try
                 {
                     Directory.CreateDirectory(outPath);
                 }
                 catch (IOException e) // Fail to create directory
                 {
                     error = string.Format("Fail to create directory: {0}", outPath);
                     LogMethod.WriteLog(LogMethod.LogType.Error, error);
                     return false;
                 }
            }

            string filename;
            string texPath, pdfPath;
            do
            {
                filename = Guid.NewGuid().ToString("D");
                texPath = string.Format(TexFileFormat, outPath, filename);
                pdfPath = string.Format(PdfFileFormat, outPath, filename);
            } while (File.Exists(texPath) || File.Exists(pdfPath));
            pdfUrl = string.Format(PdfUrlFormat, now, filename);

            // Write TEX

            LogMethod.WriteLog(LogMethod.LogType.Info, string.Format("Writing tex file: {0}", texPath));
            try
            {
                using (var texWriter = new StreamWriter(new FileStream(texPath, FileMode.Create, FileAccess.Write)))
                {
                    texWriter.WriteLine(texString);
                    texWriter.Flush();
                    texWriter.Close();
                }
            }
            catch (IOException e) // Fail to write tex file
            {
                error = string.Format("Fail to write tex file: {0}", texPath);
                LogMethod.WriteLog(LogMethod.LogType.Error, error);
                return false;
            }

            // Gen PDF

            try
            {
                var cmd = new Process
                    {
                        StartInfo =
                            {
                                FileName = exeFile,
                                Arguments = string.Format(ArgumentFormat, outPath, filename),
                                UseShellExecute = false,
                                RedirectStandardInput = true,
                                RedirectStandardOutput = true,
                                CreateNoWindow = true,
                                WindowStyle = ProcessWindowStyle.Hidden
                            }
                    };
                cmd.Start();
                var output = cmd.StandardOutput.ReadToEnd().Replace("
", "");
                var parten = @"Output written on " + pdfPath.Replace(@"", "/") + @" (d+ page).";
                // Check if processing is not successfull
                if (!Regex.IsMatch(output, parten))
                {
                    error = string.Format("Fail to gen pdf file: {0}", texPath);
                    LogMethod.WriteLog(LogMethod.LogType.Error, error);
                    return false;
                }

                // Delete unused file
                foreach (var ext in new[] { ".tex", ".aux", ".log" })
                {
                    var tmpFilePath = string.Format(FileFormatWithoutExtension, outPath, filename) + ext;
                    try
                    {
                        File.Delete(tmpFilePath);
                    }
                    catch (IOException e)
                    {
                    }
                }
            }
            catch (Exception e)
            {
                error = string.Format("Fail to gen pdf file: {0}", texPath);
                LogMethod.WriteLog(LogMethod.LogType.Error, error);
                return false;
            }

            return true;
        }
    }

在其中如果有什么问题,请留言很高兴为你解答。相互提高靠的就是你的一份真诚。本文原创,请尊重版权谢谢。

原文地址:https://www.cnblogs.com/jianrong-zheng/p/3413828.html