using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Word = Microsoft.Office.Interop.Word; using HY.Common.Configuration; using System.Net; using System.Text; using System.IO; using HY.Common.Utils; using System.Data; using HC.ReportPluginsHandler.BusinessComponent; using Microsoft.Office.Interop.Word; namespace HC.Web.PluginsFor2.ReportWeb.Page.LoanReimReqiestForm { public partial class LoanReimlPrint : System.Web.UI.Page { LoanReimlPrintBC eab = new LoanReimlPrintBC(); LoanReimReqiestFormBC bc = new LoanReimReqiestFormBC(); protected void Page_Load(object sender, EventArgs e) { HY.Common.Utils.Logger.Log.Info("開始批量打印"); object filename = ""; HY.Common.Utils.Logger.Log.Info("filename:" + filename); Object Nothing = System.Reflection.Missing.Value; HY.Common.Utils.Logger.Log.Info("Nothing:" + Nothing); //Word.Application WordApp = new Word.ApplicationClass();//實例化word Word.Application WordApp = new Word.ApplicationClass(); HY.Common.Utils.Logger.Log.Info("WordApp:" + WordApp); Word._Application oWord = new Word.Application(); //創建Word文檔 Word._Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); if (WordApp.ActiveWindow.ActivePane.View.Type == WdViewType.wdNormalView || WordApp.ActiveWindow.ActivePane.View.Type == WdViewType.wdOutlineView) { WordApp.ActiveWindow.ActivePane.View.Type = WdViewType.wdPrintView; } WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader; WordApp.Selection.HeaderFooter.LinkToPrevious = false; WordApp.Selection.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleNone; //wdlinestyle.wdlinestylenone; WordDoc.ActiveWindow.ActivePane.Selection.InsertAfter("\n\n………………………………………………………………………財務裝訂線……………………………………………………………………\n"); //跳出頁眉設置 WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; try { SetPage(WordApp, WordDoc, "豎版", 20.3, 29.7, 1, 1, 1, 1); HY.Common.Utils.Logger.Log.Info("WordDoc:" + WordDoc); string name = "報銷報表" + DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.ToLongTimeString().Replace(":", "") + ".docx";//創建生成文件名字 HY.Common.Utils.Logger.Log.Info("name" + name); string CreateFilePath = ConfigurationManager.AppSettings["CreateFilePath"]; HY.Common.Utils.Logger.Log.Info("CreateFilePath" + CreateFilePath); filename = CreateFilePath + name; //文件保存路徑 HY.Common.Utils.Logger.Log.Info("filename" + filename); string PrintType = Context.Request["PrintType"].ToString(); int index = 0; string[] SerialNumberArr = Context.Request["Folio"].Substring(0, Context.Request["Folio"].ToString().Length - 1).Split(','); string[] ProcInstIDArr = Context.Request["ProcInstID"].Substring(0, Context.Request["ProcInstID"].ToString().Length - 1).Split(',');//掛賬Id string[] ProcName = Context.Request["ProcName"].Substring(0, Context.Request["ProcName"].ToString().Length - 1).Split(',');//付款Id for (int i = 0; i < ProcInstIDArr.Length; i++) { #region 生成條形碼 Logger.Log.Info("***********************Start****************************"); string sn = SerialNumberArr[i]; System.Guid guid = new Guid(); guid = Guid.NewGuid(); string str = guid.ToString(); CreateBmp(sn, CreateFilePath, str); Logger.Log.Info("***********************End****************************"); #endregion DataSet ds = eab.GetBatchPrint(ProcInstIDArr[i], ProcName[i]); PrintWord(Nothing, WordDoc, CreateFilePath, ProcInstIDArr.Length, ProcName[i], i, sn, str, ds,index); index++; } WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); WordApp = null; HY.Common.Utils.Logger.Log.Info("SaveAs" + filename); } catch (Exception ex) { HY.Common.Utils.Logger.Log.Info("error" + ex.ToString()); } finally { WordDoc.Close(ref Nothing, ref Nothing, ref Nothing); oWord.Quit(ref Nothing, ref Nothing, ref Nothing); KillWordProcess(); } Response.Redirect("/PluginsFor2/ProjectWeb/Page/ExcelBatchApproval/DownLoadFilePrint.aspx?filename=" + System.Web.HttpUtility.UrlEncode(filename.ToString()));//將檔案名稱傳送到另一個頁面 Context.Response.Write("{success:'true',fileName:'" + filename.ToString() + "'}"); } private static void PrintWord(Object Nothing, Word._Document WordDoc, string CreateFilePath, int ProcInstIDArrLenth, string ProcName, int i, string sn, string str, DataSet ds,int index) { System.Data.DataTable dtBasicInfo = ds.Tables[0];//基本信息 System.Data.DataTable dtAllHistorysInfo = ds.Tables[4];//審批歷史記錄 dtAllHistorysInfo = ds.Tables[7]; System.Data.DataTable dtHistorysInfo = new System.Data.DataTable(); dtHistorysInfo.Columns.Add("CZXMJL");//由於用不到列名,所以隨便寫,只要保證列數夠用就可 dtHistorysInfo.Columns.Add("BMXMJL"); dtHistorysInfo.Columns.Add("ZYSP"); dtHistorysInfo.Columns.Add("CZSP"); dtHistorysInfo.Columns.Add("CZXMJL2"); dtHistorysInfo.Columns.Add("BMXMJL2"); dtHistorysInfo.Columns.Add("ZYSP2"); dtHistorysInfo.Columns.Add("CZSP2"); if (dtAllHistorysInfo.Rows.Count > 0) { string[] hiArr = new string[8]; hiArr[0] = "審批人"; hiArr[1] = "流程節點"; hiArr[2] = "審批意見"; hiArr[3] = "審批時間"; hiArr[4] = "審批人"; hiArr[5] = "流程節點"; hiArr[6] = "審批意見"; hiArr[7] = "審批時間"; dtHistorysInfo.Rows.Add(hiArr[0], hiArr[1], hiArr[2], hiArr[3], hiArr[4], hiArr[5], hiArr[6], hiArr[7]); for (int k = 0; k < dtAllHistorysInfo.Rows.Count; k++) { string actName = dtAllHistorysInfo.Rows[k]["ActName"].ToString(); string approvalPerson = dtAllHistorysInfo.Rows[k]["Emp_Name"].ToString(); string FinalAction = dtAllHistorysInfo.Rows[k]["FinalAction"].ToString(); string approvalDate = dtAllHistorysInfo.Rows[k]["ActivityFinishDate"].ToString(); hiArr[0] = approvalPerson; hiArr[1] = actName; hiArr[2] = FinalAction; hiArr[3] = approvalDate; hiArr[4] = ""; hiArr[5] = ""; hiArr[6] = ""; hiArr[7] = ""; if (k + 1 < dtAllHistorysInfo.Rows.Count) { hiArr[4] = dtAllHistorysInfo.Rows[k + 1]["Emp_Name"].ToString(); hiArr[5] = dtAllHistorysInfo.Rows[k + 1]["ActName"].ToString(); hiArr[6] = dtAllHistorysInfo.Rows[k + 1]["FinalAction"].ToString(); hiArr[7] = dtAllHistorysInfo.Rows[k + 1]["ActivityFinishDate"].ToString(); } dtHistorysInfo.Rows.Add(hiArr[0], hiArr[1], hiArr[2], hiArr[3], hiArr[4], hiArr[5], hiArr[6], hiArr[7]); k++; } } if (ProcName == "費用報銷單") { #region 費用報銷單打印 #region 數據處理 //將取出來的基本信息轉換為想要的格式 System.Data.DataTable dtBasicInfo0 = new System.Data.DataTable(); dtBasicInfo0.Columns.Add("1"); dtBasicInfo0.Columns.Add("2"); dtBasicInfo0.Columns.Add("3"); dtBasicInfo0.Columns.Add("4"); if (dtBasicInfo.Rows.Count > 0) { for (int j = 0; j < dtBasicInfo.Rows.Count; j++) { dtBasicInfo0.Rows.Add("申請人", dtBasicInfo.Rows[j]["Applicant"], "部門", dtBasicInfo.Rows[j]["Dept"]); dtBasicInfo0.Rows.Add("工號", dtBasicInfo.Rows[j]["Emp_Code"], "職務/職稱", dtBasicInfo.Rows[j]["Post"]); dtBasicInfo0.Rows.Add("電話", dtBasicInfo.Rows[j]["ApplicantTel"], "手機", dtBasicInfo.Rows[j]["Phone"]); dtBasicInfo0.Rows.Add("處長", dtBasicInfo.Rows[j]["Director"], "部長", dtBasicInfo.Rows[j]["Minister"]); } } #endregion string pictureName = ConfigurationManager.AppSettings["logImg"]; InsertPicture(WordDoc, pictureName, 95, 38); InsertText(WordDoc, " 費用報銷單", new System.Drawing.Font("Arial", 12, System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, false); InsertPicture(WordDoc, CreateFilePath + str, 250, 38); InsertText(WordDoc, "", new System.Drawing.Font("Arial", 9, System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, true); InsertText(WordDoc, "申請人信息", new System.Drawing.Font("Arial", 9, System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, false); double[] dtBasicInfoWidthArr = new double[4] { 2.5, 6.77, 2.5, 6.76 };//設置表格的寬度 InsertTable(WordDoc, dtBasicInfo0, true, dtBasicInfoWidthArr,9); InsertText(WordDoc, "審批歷史記錄", new System.Drawing.Font("Arial", 9, System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, false); double[] dtBasic = new double[8] { 1.35, 3.36, 1.85, 2.9, 1.35, 3.37, 1.65, 2.9 };//設置表格的寬度 InsertTable(WordDoc, dtHistorysInfo, true, dtBasic, 9); InsertText(WordDoc, "注:本借款單適用於除差旅費之外備用金借款以及一次性付款項目的借款", new System.Drawing.Font("Arial", 9, System.Drawing.FontStyle.Regular), Word.WdParagraphAlignment.wdAlignParagraphLeft, true, true); if (ProcInstIDArrLenth - 1 != i) { InsertBreak(WordDoc, Nothing); } #endregion } } //生成條形碼 private static void CreateBmp(string sn, string CreateFilePath, string guid) { HttpWebRequest req = null; HttpWebResponse resp = null; Stream stream = null; ASCIIEncoding encoding = new ASCIIEncoding(); string webString = ConfigurationManager.AppSettings["webString"]; String postData = "method=barcode" + "&barcode=" + sn; byte[] data = encoding.GetBytes(postData); req = (HttpWebRequest)WebRequest.Create(webString + "BmpHandler.ashx"); req.Method = "POST"; req.Timeout = 5000; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = data.Length; stream = req.GetRequestStream(); stream.Write(data, 0, data.Length); resp = (HttpWebResponse)req.GetResponse(); Stream streamOut = resp.GetResponseStream(); FileStream fs = new FileStream(CreateFilePath + guid, FileMode.Create); //實例化一個StreamWriter-->與fs相關聯 BinaryWriter sw = new BinaryWriter(fs); byte[] bArr = new byte[1024]; int read = 0; do { read = streamOut.Read(bArr, 0, 1024); sw.Write(bArr, 0, read); } while (read > 0); //清空緩沖區 sw.Flush(); //關閉流 sw.Close(); fs.Close(); } #region - 頁面設置 - public static void SetPage(Word.Application oWord, Word._Document oDoc, string orientation, double width, double height, double topMargin, double leftMargin, double rightMargin, double bottomMargin) { Logger.Log.Info("Word.Name" + oWord.Name); Logger.Log.Info("oDoc" + oDoc); oDoc.PageSetup.PageWidth = oWord.CentimetersToPoints((float)width); oDoc.PageSetup.PageHeight = oWord.CentimetersToPoints((float)height); if (orientation == "橫板") { oDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape; } oDoc.PageSetup.TopMargin = (float)(topMargin * 25);//上邊距 oDoc.PageSetup.LeftMargin = (float)(leftMargin * 25);//左邊距 oDoc.PageSetup.RightMargin = (float)(rightMargin * 25);//右邊距 oDoc.PageSetup.BottomMargin = (float)(bottomMargin * 25);//下邊距 } #endregion #region - 插入分頁符 - public static void InsertBreak(Word._Document WordDoc, Object Nothing) { Word.Paragraph para; para = WordDoc.Content.Paragraphs.Add(ref Nothing); object pBreak = (int)Word.WdBreakType.wdSectionBreakNextPage; para.Range.InsertBreak(ref pBreak); para.Range.Delete(); } public static void DeleteBreak(Word.Application wordApp, Object Nothing) { Word.Range range1, range2; // 跳轉種類 object objWhat = Word.WdGoToItem.wdGoToPage; // 跳轉位置 object objWhich = Word.WdGoToDirection.wdGoToLast; // 轉向最后一頁 wordApp.Selection.GoTo(ref objWhat, ref objWhich, ref Nothing, ref Nothing); // Range取得 range1 = wordApp.Selection.Range; range2 = wordApp.ActiveDocument.Range(ref Nothing, ref Nothing); object start = range1.Start; object end = range2.End; // 刪除最后一頁 wordApp.ActiveDocument.Range(ref start, ref end).Delete(ref Nothing, ref Nothing); } #endregion #region - 插入文本 - public static bool InsertText(Word._Document oDoc, string strText, System.Drawing.Font font, Word.WdParagraphAlignment wdAlign, bool isAftre) { try { Word.Range rng = oDoc.Content; int lenght = oDoc.Characters.Count - 1; object start = lenght; object end = lenght; rng = oDoc.Range(ref start, ref end); if (isAftre == true) { strText += "\r\n"; } rng.Text = strText; rng.Font.Name = font.Name; rng.Font.Size = font.Size; if (font.Style == System.Drawing.FontStyle.Bold) { rng.Font.Bold = 1; } //設置單元格中字體為粗體 rng.ParagraphFormat.Alignment = wdAlign;//設置文本對齊格式(左對齊,右對齊,居中) return true; } catch (Exception) { return false; } } #endregion #region -插入表格 public static bool InsertTable(Word._Document oDoc, System.Data.DataTable dt, bool haveBorder, double[] colWidths,int size) { try { object Nothing = System.Reflection.Missing.Value; int lenght = oDoc.Characters.Count - 1; object start = lenght; object end = lenght; //表格起始坐標 Word.Range tableLocation = oDoc.Range(ref start, ref end); //添加Word表格 Word.Table table = oDoc.Tables.Add(tableLocation, dt.Rows.Count, dt.Columns.Count, ref Nothing, ref Nothing); if (colWidths != null) { for (int i = 0; i < colWidths.Length; i++) { table.Columns[i + 1].Width = (float)(28.5F * colWidths[i]); } } //設置TABLE的樣式 table.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAtLeast; //table.Rows.Height = oWord.CentimetersToPoints(float.Parse("0.8")); table.Range.Font.Size = size; table.Range.Font.Name = "Arial"; table.Range.Font.Bold = 0; table.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; table.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; if (haveBorder == true) { //設置外框樣式 table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; //樣式設置結束 } //循環store的行和列創建Table for (int row = 0; row < dt.Rows.Count; row++) { for (int col = 0; col < dt.Columns.Count; col++) { table.Cell(row + 1, col + 1).Range.Text = dt.Rows[row][col].ToString(); var text = table.Cell(row + 1, col + 1).Range.Text; if (text.Length > 3) { if (text.Substring(text.Length - 3) == "\r\r\a") { table.Cell(row + 1, col + 1).Range.Text = text.Substring(0, text.Length - 3); } if (table.Cell(row + 1, 1).Range.Text == "匯率填寫備注\r\a") { table.Cell(row + 1, 2).Merge(table.Cell(row + 1, 5)); } } } } if (table.Cell(1, 1).Range.Text == "關聯預算審批流程\r\a")//判斷哪些表格需要合並單元格,先這樣子寫,這樣寫不好,以后想辦法 { table.Cell(1, 2).Merge(table.Cell(1, 3)); table.Cell(2, 3).Merge(table.Cell(2, 4)); table.Cell(2, 3).Merge(table.Cell(2, 4)); table.Cell(3, 3).Merge(table.Cell(3, 4)); table.Cell(3, 3).Merge(table.Cell(3, 4)); table.Cell(4, 2).Merge(table.Cell(4, 3)); } return true; } catch (Exception e) { Console.WriteLine(e.ToString()); return false; } finally { } } #endregion #region - 插入圖片 - public static bool InsertPicture(Word._Document oDoc, string pictureName, float width, float height) { try { Word.Range rng = oDoc.Content; int lenght = oDoc.Characters.Count - 1; object start = lenght; object end = lenght; rng = oDoc.Range(ref start, ref end); Object range = rng; object LinkToFile = false; object SaveWithDocument = true; Word.InlineShape shape = oDoc.Application.ActiveDocument.InlineShapes.AddPicture(pictureName, ref LinkToFile, ref SaveWithDocument, ref range);//插入圖片 shape.Width = width; shape.Height = height; return true; } catch (Exception e) { HY.Common.Utils.Logger.Log.Info("InsertPicture:" + e.ToString()); return false; } } #endregion #region - 清除word進程 - /**/ /// <summary> /// 清除word進程 /// </summary> public static void KillWordProcess() { System.Diagnostics.Process[] myPs; myPs = System.Diagnostics.Process.GetProcesses(); foreach (System.Diagnostics.Process p in myPs) { if (p.Id != 0) { string myS = "WINWORD.EXE" + p.ProcessName + " ID:" + p.Id.ToString(); try { if (p.Modules != null) if (p.Modules.Count > 0) { System.Diagnostics.ProcessModule pm = p.Modules[0]; myS += "/n Modules[0].FileName:" + pm.FileName; myS += "/n Modules[0].ModuleName:" + pm.ModuleName; myS += "/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString(); if (pm.ModuleName.ToLower() == "winword.exe") p.Kill(); } } catch { } finally { } } } } #endregion } }