Latex轉換之PDF

近期一直在作如何使用latex將模板轉換成PDF.如今寫下在項目中如何實現。app

1.首先你先進官網下載http://www.miktex.org/download。我用的是以下圖所示。ui

在下載好的MikTeX找到以下目錄(E:\Software)\MiKTeX 2.9\miktex\bin\x64中的miktex-xetex.spa

2.本身新建一個模板.tex文件和一個.bat文件。其中在.bat文件中寫入miktex-2.9.4813\miktex\bin\miktex-xetex.exe -undump=xelatex test.tex(這是你本身所寫的模板文件)code

下面是我本身項目中的一個模板,個人.tex文件以下orm

%!Tex Program = xelatex
\documentclass[a4paper]{article}
\usepackage{xltxtra}
\setmainfont[Mapping=tex-text]{Microsoft YaHei}
\begin{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}blog

3.雙擊.bat文件進行運行,運行結果以下。cmd

 

其中調用xetex.cmd口令程序代碼以下。string

 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("\r\n", "");
                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;
        }
    }

 

在其中若是有什麼問題,請留言很高興爲你解答。相互提升靠的就是你的一份真誠。本文原創,請尊重版權謝謝。it

相關文章
相關標籤/搜索