You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
3.5 KiB

  1. using log4net;
  2. using OT.COM.ArsenalDB;
  3. using System;
  4. using System.Diagnostics;
  5. using System.IO;
  6. namespace CounsellorBL
  7. {
  8. public static class ReportExtension
  9. {
  10. private static ILog _inst = null;
  11. private static ILog Logger
  12. {
  13. get
  14. {
  15. if (_inst == null)
  16. {
  17. _inst = LogManager.GetLogger(typeof(ReportExtension));
  18. }
  19. return _inst;
  20. }
  21. }
  22. /// <summary>
  23. /// 轉換為Pdf
  24. /// </summary>
  25. /// <param name="timeout">轉換逾時秒數</param>
  26. /// <param name="tmpFileFullPath">檔案路徑</param>
  27. /// <returns></returns>
  28. public static string ConvertToPdf(int timeout, string tmpFileFullPath, out string pdfFileFullPath)
  29. {
  30. // 經由轉換程式處理
  31. var pdfProcess = new Process();
  32. pdfProcess.StartInfo.FileName = CustomizeDBMgr.SettingData["PdfConverterFileName"];
  33. // LibreOffice有bug,如果路徑用"\"無法判別,必須改用"/",例如"C:\ABC\"要用"C:/ABC/"
  34. pdfProcess.StartInfo.Arguments = string.Format(CustomizeDBMgr.SettingData["PdfConverterArguments"],
  35. tmpFileFullPath.Replace('\\', '/'),
  36. Path.GetDirectoryName(tmpFileFullPath).Replace('\\', '/'));
  37. pdfProcess.StartInfo.CreateNoWindow = false;
  38. pdfProcess.StartInfo.UseShellExecute = false;
  39. Logger.Info("FileName:"+pdfProcess.StartInfo.FileName+ " "+ pdfProcess.StartInfo.Arguments);
  40. try
  41. {
  42. // PDF開始轉換的時間
  43. var startConvertTime = DateTime.Now;
  44. pdfProcess.Start();
  45. if (pdfProcess.WaitForExit(timeout * 1000)) // 逾時秒數
  46. {
  47. // 取回PDF資料
  48. pdfFileFullPath = Path.ChangeExtension(tmpFileFullPath, ".pdf");
  49. var duration = DateTime.Now - startConvertTime;
  50. //Logger.InfoFormat("轉換PDF [{0}] 花費 {1:n2} 秒 ({2:n2} 毫秒)", pdfFileFullPath, duration.TotalSeconds, duration.TotalMilliseconds);
  51. // 因為lag關係,可能要等一段時間檔案才會真正產生
  52. // 增加一點等待時間
  53. for (var retry = 0; retry < 10; retry++)
  54. {
  55. var exist = File.Exists(pdfFileFullPath);
  56. if (exist)
  57. {
  58. return null; // 回傳null算正確
  59. }
  60. System.Threading.Thread.Sleep(200);
  61. }
  62. // 等候太久,回傳失敗
  63. Logger.Error("無法取回PDF " + pdfFileFullPath);
  64. return "轉換逾時,無法取回PDF";
  65. }
  66. else
  67. {
  68. // 等候太久,可能是轉換失敗
  69. Logger.Error("轉換PDF逾時 " + tmpFileFullPath);
  70. pdfFileFullPath = null;
  71. return "轉換逾時";
  72. }
  73. }
  74. catch (Exception e)
  75. {
  76. Logger.Error("轉換PDF發生錯誤", e);
  77. pdfFileFullPath = null;
  78. return "轉換PDF時發生錯誤" + e.Message;
  79. }
  80. finally
  81. {
  82. pdfProcess.Dispose();
  83. }
  84. }
  85. }
  86. }