Beispiel #1
0
        /// <summary>
        /// 列印資料
        /// </summary>
        /// <param name="print_title">列印標題</param>
        /// <param name="template_file">樣版檔案</param>
        /// <param name="replace_dic_list">List(Dictionary)資料</param>
        /// <param name="output_type">輸出類型(預設PDF)</param>
        /// <returns>byte[]</returns>
        public byte[] print(string print_title, string template_file, List <Dictionary <string, string> > replace_dic_list, string output_type = "pdf")
        {
            byte[] print_byte = null;
            //新增一個word檔案並加載,樣版檔案
            Spire.Doc.Document document = new Spire.Doc.Document();

            //取得副檔名
            string extension = string.IsNullOrEmpty(Path.GetExtension(template_file)) ? "" : Path.GetExtension(template_file).ToLower();

            List <byte[]> pdf_byte_list = new List <byte[]>();
            int           loop_i        = 0;

            foreach (Dictionary <string, string> dic in replace_dic_list)
            {
                switch (extension)
                {
                case ".docx":
                    document.LoadFromFileInReadMode(template_file, Spire.Doc.FileFormat.Docx2013);
                    break;

                default:
                    break;
                }
                //置換識別字,[$變數名稱$]
                Regex regEx = new Regex(@"\[\$\w*\$\]");
                //尋找識別字
                TextSelection[] selections = document.FindAllPattern(regEx);
                foreach (TextSelection ts in selections)
                {
                    TextRange range        = ts.GetAsOneRange();
                    string    sel_text     = ts.SelectedText.Replace("[$", "").Replace("$]", "");
                    string    replace_text = range.Text;

                    //嘗試置換字符串
                    dic.TryGetValue(sel_text, out replace_text);
                    range.Text = replace_text;
                }
                using (MemoryStream ms = new MemoryStream())
                {
                    document.SaveToStream(ms, Spire.Doc.FileFormat.PDF);
                    //save to byte array
                    pdf_byte_list.Add(ms.ToArray());
                    ms.Close();
                }
                loop_i++;
            }//foreach

            //合併PDF
            print_byte = MergePDFFiles(pdf_byte_list);
            return(print_byte);
        }//print