一.安裝libreOffice
點擊官網下載libreOffice
二.創建一個新的項目LibreOffice
創建一個新的項目,方便后面調用
添加下面代碼
public class OfficeConvert { static string getLibreOfficePath() { switch (Environment.OSVersion.Platform) { case PlatformID.Unix: return "/usr/bin/soffice"; case PlatformID.Win32NT: string binaryDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); return binaryDirectory + "\\Windows\\program\\soffice.exe"; default: throw new PlatformNotSupportedException("你的系統暫不支持!"); } } public static void ToPdf(string officePath, string outPutPath) { //獲取libreoffice命令的路徑 string libreOfficePath = getLibreOfficePath(); ProcessStartInfo procStartInfo = new ProcessStartInfo(libreOfficePath, string.Format("--convert-to pdf --outdir {0} --nologo {1}", outPutPath, officePath)); procStartInfo.RedirectStandardOutput = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = true; procStartInfo.WorkingDirectory = Environment.CurrentDirectory; //開啟線程 Process process = new Process() { StartInfo = procStartInfo, }; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { throw new LibreOfficeFailedException(process.ExitCode); } } } public class LibreOfficeFailedException : Exception { public LibreOfficeFailedException(int exitCode) : base(string.Format("LibreOffice錯誤 {0}", exitCode)) { } }
三.將libreOffice的安裝文件復制到自己項目host下面的如下路徑
本操作主要是通過調用libreOffice的命令行方法,將office轉化為pdf
四、當將程序發布到iis時,需要將應用程序池中的高級設置設置為true。
這個問題坑了我一個星期,如果不設置,進程會一直運行,不退出。