Exemplo n.º 1
0
 /// <summary>
 /// Convert doc or docx to html with picture files
 /// </summary>
 /// <param name="inputFileName">Absolute name of input file</param>
 /// <param name="outputFolder">Folder for saving results</param>
 /// <param name="newFileName">Relative filename of new html</param>
 public static void ConvertToHtml(string inputFileName, string outputFolder, string newFileName, Dictionary <string, string> parameters)
 {
     if (!Directory.Exists(outputFolder))
     {
         Directory.CreateDirectory(outputFolder);
     }
     Spire.Doc.Document document = new Spire.Doc.Document(inputFileName);
     using (var stream = new MemoryStream())
     {
         document.SaveToStream(stream, Spire.Doc.FileFormat.Html);
         string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());
         if (result.IndexOf(replaceValueDocx) < 0 && result.IndexOf(replaceValueDoc) < 0)
         {
             result = System.Text.Encoding.UTF8.GetString(stream.ToArray()).Replace(replaceValueDocx, "").Replace(replaceValueDoc, "").Replace(replaceValue, "");
         }
         else
         {
             result = System.Text.Encoding.UTF8.GetString(stream.ToArray()).Replace(replaceValueDocx, "").Replace(replaceValueDoc, "");
         }
         AddImages(document, outputFolder, ref result);
         File.WriteAllText(outputFolder + "/" + newFileName, result, Encoding.UTF8);
         result = null;
     }
     document.Dispose();
 }
Exemplo n.º 2
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
Exemplo n.º 3
0
        static Stream BRtfDocx(byte[] byteArray)
        {
            MemoryStream ms       = new MemoryStream(byteArray);
            MemoryStream msout    = new MemoryStream();
            StreamReader sReader  = new StreamReader(ms);
            var          document = new Spire.Doc.Document();

            //document.LoadFromFile(@"test-doc.rtf");
            ms.Seek(0, SeekOrigin.Begin);
            document.LoadRtf(ms, Encoding.UTF8);
            document.SaveToStream(msout, FileFormat.Docx);
            msout.Seek(0, SeekOrigin.Begin);
            //StreamReader reader = new StreamReader(msout);
            //string text = reader.ReadToEnd();
            return(msout);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Convert doc or docx to html with base64 pictures
        /// </summary>
        /// <param name="inputFileName">Absolute name of input file</param>
        /// <param name="outputFileName">Absolute name of output file</param>
        public static void ConvertToHtml(string inputFileName, string outputFileName)
        {
            Spire.Doc.Document document = new Spire.Doc.Document(inputFileName);
            using (var stream = new MemoryStream())
            {
                string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                document.SaveToStream(stream, Spire.Doc.FileFormat.Html);
                if (result.IndexOf(replaceValueDocx) < 0 && result.IndexOf(replaceValueDoc) < 0)
                {
                    result = System.Text.Encoding.UTF8.GetString(stream.ToArray()).Replace(replaceValueDocx, "").Replace(replaceValueDoc, "").Replace(replaceValue, "");
                }
                else
                {
                    result = System.Text.Encoding.UTF8.GetString(stream.ToArray()).Replace(replaceValueDocx, "").Replace(replaceValueDoc, "");
                }
                result = ReplaceImages(document, result);

                File.WriteAllText(outputFileName, result, Encoding.UTF8);
                result = null;
            }
            document.Dispose();
        }
Exemplo n.º 5
0
        /// <summary>
        /// 透過既有的套印檔匯出 Word 文件 (以「編輯書籤內容」方式套印)
        /// </summary>
        /// <param name="result">回傳: 執行結果</param>
        /// <param name="msg">回傳: 訊息</param>
        /// <returns>串流資訊</returns>
        public byte[] ExportResumeByDocx_Bookmark(out bool result, out string msg)
        {
            result = true;
            msg    = "";
            MemoryStream ms = new MemoryStream();

            try
            {
                Spire.Doc.Document document = new Spire.Doc.Document();

                //載入套印檔
                //注意: 實際運作時,若同一時間有兩位以上使用者同時進行套印,會產生「無法開啟已開啟檔案」的錯誤
                //建議實作時,一個使用者執行匯出動作時先複製一個套印檔,完成套印後再將複製的檔案刪除,即可避開錯誤
                document.LoadFromFile(HttpContext.Current.Server.MapPath("~/App_Data/MyResumeSample_Bookmark.docx"));

                #region 定義樣式

                //定義樣式 BasicStyle: 一般段落文字
                ParagraphStyle style = new ParagraphStyle(document)
                {
                    Name = "Basic"
                };
                //style.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Justify;
                style.CharacterFormat.FontName = "標楷體";
                style.CharacterFormat.FontSize = 12;
                document.Styles.Add(style);

                #endregion

                //取得要套印的內容
                Resume model = new Resume();

                #region 套印內容

                BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);

                Spire.Doc.Bookmark bookmark = document.Bookmarks.FindByName("NAME");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("NAME");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Name) ? "" : model.Name, false);
                }
                bookmark = document.Bookmarks.FindByName("GENDER");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("GENDER");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Gender) ? "" : model.Gender, false);
                }
                bookmark = document.Bookmarks.FindByName("EMAIL");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("EMAIL");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Email) ? "" : model.Email, false);
                }
                bookmark = document.Bookmarks.FindByName("ADDRESS");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("ADDRESS");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Address) ? "" : model.Address, false);
                }
                bookmark = document.Bookmarks.FindByName("PHONE");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("PHONE");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Phone) ? "" : model.Phone, false);
                }
                bookmark = document.Bookmarks.FindByName("MOBILE");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("MOBILE");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Mobile) ? "" : model.Mobile, false);
                }



                Spire.Doc.Section tempSection = document.AddSection();
                string            html;
                ParagraphBase     replacementFirstItem;
                ParagraphBase     replacementLastItem;
                TextBodySelection selection;
                TextBodyPart      part;

                //HTML Contents: Desciprion1
                bookmark = document.Bookmarks.FindByName("DESCRIPTION1");
                if (bookmark != null)
                {
                    html = string.IsNullOrEmpty(model.Description1) ? "" : HttpUtility.HtmlDecode(model.Description1);
                    tempSection.AddParagraph().AppendHTML(html);
                    replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
                    replacementLastItem  = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
                    selection            = new TextBodySelection(replacementFirstItem, replacementLastItem);
                    //將內容各段落套用指定的樣式
                    for (int i = 0; i < tempSection.Paragraphs.Count; i++)
                    {
                        tempSection.Paragraphs[i].ApplyStyle("Basic");
                    }
                    part = new TextBodyPart(selection);

                    // locate the bookmark
                    bookmarkNavigator.MoveToBookmark("DESCRIPTION1");
                    //replace the content of bookmark
                    bookmarkNavigator.ReplaceBookmarkContent(part);
                    //remove temp section
                    document.Sections.Remove(tempSection);
                }

                //HTML Contents: Desciprion2
                bookmark = document.Bookmarks.FindByName("DESCRIPTION2");
                if (bookmark != null)
                {
                    tempSection = document.AddSection();
                    html        = string.IsNullOrEmpty(model.Description2) ? "" : HttpUtility.HtmlDecode(model.Description2);
                    tempSection.AddParagraph().AppendHTML(html);
                    replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
                    replacementLastItem  = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
                    selection            = new TextBodySelection(replacementFirstItem, replacementLastItem);
                    part = new TextBodyPart(selection);

                    bookmarkNavigator.MoveToBookmark("DESCRIPTION2");
                    bookmarkNavigator.ReplaceBookmarkContent(part);
                    document.Sections.Remove(tempSection);
                }

                //圖片
                bookmark = document.Bookmarks.FindByName("IMG");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("IMG");
                    Spire.Doc.Section             section_img   = document.AddSection();
                    Spire.Doc.Documents.Paragraph paragraph_img = section_img.AddParagraph();
                    Image      img     = Image.FromFile(HttpContext.Current.Server.MapPath("~/App_Data/Penguins.jpg"));
                    DocPicture picture = paragraph_img.AppendPicture(img);

                    bookmarkNavigator.InsertParagraph(paragraph_img);
                    document.Sections.Remove(section_img);
                }
                #endregion

                #region 動態新增表格

                if (model.JobHistory.Count > 0)
                {
                    Spire.Doc.Section s      = document.AddSection();
                    Spire.Doc.Table   table  = s.AddTable(true);
                    string[]          Header = { "序號", "任職公司", "職稱", "開始時間", "結束時間" };

                    //Add Cells
                    table.ResetCells(model.JobHistory.Count + 1, Header.Length);

                    //Header Row
                    TableRow FRow = table.Rows[0];
                    FRow.IsHeader = true;
                    for (int i = 0; i < Header.Length; i++)
                    {
                        Spire.Doc.Documents.Paragraph p = FRow.Cells[i].AddParagraph();
                        FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        p.Format.HorizontalAlignment = HorizontalAlignment.Center;

                        TextRange TR = p.AppendText(Header[i]);
                        TR.CharacterFormat.Bold = true;
                    }

                    //Data Row
                    model.JobHistory = model.JobHistory.OrderBy(x => x.StartDT).ToList();
                    for (int r = 0; r < model.JobHistory.Count; r++)
                    {
                        TableRow DataRow = table.Rows[r + 1];
                        string[] data    = new string[] { (r + 1).ToString(), model.JobHistory[r].CompanyName, model.JobHistory[r].JobTitle, (model.JobHistory[r].StartDT.HasValue ? model.JobHistory[r].StartDT.Value.ToShortDateString() : ""), (model.JobHistory[r].EndDT.HasValue ? model.JobHistory[r].EndDT.Value.ToShortDateString() : "") };

                        //Columns.
                        for (int c = 0; c < data.Length; c++)
                        {
                            //Cell Alignment
                            DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

                            //Fill Data in Rows
                            Spire.Doc.Documents.Paragraph p2 = DataRow.Cells[c].AddParagraph();
                            TextRange TR2 = p2.AppendText(data[c]);

                            //Format Cells
                            p2.Format.HorizontalAlignment = HorizontalAlignment.Center;
                        }
                    }

                    bookmarkNavigator.MoveToBookmark("TABLE");
                    bookmarkNavigator.InsertTable(table);
                }

                #endregion

                #region 套用樣式

                //套用文章段落樣式
                for (int s = 0; s < document.Sections.Count; s++)
                {
                    Spire.Doc.Section sections = document.Sections[s];
                    //套用文章段落樣式
                    for (int p = 0; p < sections.Paragraphs.Count; p++)
                    {
                        Spire.Doc.Documents.Paragraph pgh = sections.Paragraphs[p];
                        pgh.ApplyStyle("Basic");
                        pgh.Format.BeforeSpacing = 12;
                    }

                    //套用表格樣式
                    for (int t = 0; t < document.Sections[s].Tables.Count; t++)
                    {
                        Spire.Doc.Table table = (Spire.Doc.Table)document.Sections[s].Tables[t];
                        table.PreferredWidth            = new PreferredWidth(WidthType.Percentage, 100);
                        table.TableFormat.IsAutoResized = true;

                        //set table border
                        //table.TableFormat.Borders.Right.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Left.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Top.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Horizontal.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Vertical.BorderType = Spire.Doc.Documents.BorderStyle.Thick;

                        for (int tr = 0; tr < table.Rows.Count; tr++)
                        {
                            for (int td = 0; td < table.Rows[tr].Cells.Count; td++)
                            {
                                for (int t_ph = 0; t_ph < table.Rows[tr].Cells[td].Paragraphs.Count; t_ph++)
                                {
                                    table.Rows[tr].Cells[td].Paragraphs[t_ph].ApplyStyle("Basic");
                                }
                            }
                        }
                    }
                }

                #endregion

                //匯出
                document.SaveToStream(ms, FileFormat.Docx);
            }
            catch (Exception ex)
            {
                result = false;
                msg    = ex.Message;
            }

            if (result)
            {
                return(ms.ToArray());
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// 透過 HTML Tag 匯出 Word 文件
        /// </summary>
        /// <param name="result">回傳: 執行結果</param>
        /// <param name="msg">回傳: 訊息</param>
        /// <returns>串流資訊</returns>
        public byte[] ExportResumeByHtml(out bool result, out string msg)
        {
            result = true;
            msg    = "";
            MemoryStream ms = new MemoryStream();

            try
            {
                Spire.Doc.Document document = new Spire.Doc.Document();

                #region 文件內容

                //建立/取得要匯出的內容
                Resume        model = new Resume();
                StringBuilder html  = new StringBuilder();
                html.Append("Name: " + model.Name + "<br />");
                html.Append("Gender: " + model.Gender + "<br />");
                html.Append("Email: " + model.Email + "<br />");
                html.Append("Address: " + model.Address + "<br />");
                html.Append("Phone: " + model.Phone + "<br />");
                html.Append("Mobile: " + model.Mobile + "<br />");
                html.Append("Description1:<br />" + HttpUtility.HtmlDecode(model.Description1) + "<br /></p>");
                html.Append("Description2:<br />" + HttpUtility.HtmlDecode(model.Description2) + "<br /></p>");

                if (model.JobHistory.Count > 0)
                {
                    int i = 1;
                    model.JobHistory = model.JobHistory.OrderBy(x => x.StartDT).ToList();
                    html.Append("<p>簡歷</p>");
                    html.Append("<table><tr><th>項目</th><th>任職</th><th>職稱</th><th>開始時間</th><th>結束時間</th></tr>");
                    foreach (var h in model.JobHistory)
                    {
                        html.Append("<tr>");
                        html.Append("<td>" + i.ToString() + "</td>");
                        html.Append("<td>" + h.CompanyName + "</td>");
                        html.Append("<td>" + h.JobTitle + "</td>");
                        html.Append("<td>" + (h.StartDT.HasValue ? h.StartDT.Value.ToShortDateString() : "") + "</td>");
                        html.Append("<td>" + (h.EndDT.HasValue ? h.EndDT.Value.ToShortDateString() : "") + "</td>");
                        html.Append("</tr>");
                        i++;
                    }
                    html.Append("</table>");
                }

                #endregion

                //將 HTML 載入至 Document
                document.LoadHTML(new StringReader(html.ToString()), XHTMLValidationType.None);

                #region 設定樣式

                //一般段落文字
                ParagraphStyle style = new ParagraphStyle(document)
                {
                    Name = "BasicStyle"
                };
                //style.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Justify;
                style.CharacterFormat.FontName = "標楷體";
                style.CharacterFormat.FontSize = 12;
                document.Styles.Add(style);

                #endregion

                #region 套用樣式

                for (int s = 0; s < document.Sections.Count; s++)
                {
                    Spire.Doc.Section section = document.Sections[s];
                    //套用文章段落樣式
                    for (int p = 0; p < section.Paragraphs.Count; p++)
                    {
                        Spire.Doc.Documents.Paragraph pgh = section.Paragraphs[p];
                        pgh.ApplyStyle("BasicStyle");
                        pgh.Format.BeforeSpacing = 10;
                    }

                    //套用表格樣式
                    for (int t = 0; t < document.Sections[s].Tables.Count; t++)
                    {
                        Spire.Doc.Table table = (Spire.Doc.Table)document.Sections[s].Tables[t];
                        table.PreferredWidth            = new PreferredWidth(WidthType.Percentage, 100);
                        table.TableFormat.IsAutoResized = true;

                        //set table border
                        table.TableFormat.Borders.Right.BorderType      = Spire.Doc.Documents.BorderStyle.Thick;
                        table.TableFormat.Borders.Left.BorderType       = Spire.Doc.Documents.BorderStyle.Thick;
                        table.TableFormat.Borders.Top.BorderType        = Spire.Doc.Documents.BorderStyle.Thick;
                        table.TableFormat.Borders.Bottom.BorderType     = Spire.Doc.Documents.BorderStyle.Thick;
                        table.TableFormat.Borders.Horizontal.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        table.TableFormat.Borders.Vertical.BorderType   = Spire.Doc.Documents.BorderStyle.Thick;

                        for (int tr = 0; tr < table.Rows.Count; tr++)
                        {
                            for (int td = 0; td < table.Rows[tr].Cells.Count; td++)
                            {
                                for (int t_ph = 0; t_ph < table.Rows[tr].Cells[td].Paragraphs.Count; t_ph++)
                                {
                                    table.Rows[tr].Cells[td].Paragraphs[t_ph].ApplyStyle("BasicStyle");
                                }
                            }
                        }
                    }
                }

                #endregion

                //匯出
                document.SaveToStream(ms, FileFormat.Docx);
            }
            catch (Exception ex)
            {
                msg    = ex.Message;
                result = false;
            }

            if (result)
            {
                return(ms.ToArray());
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// 透過既有的套印檔匯出 Word 文件 (以「取代文字」方式套印)
        /// </summary>
        /// <param name="result">回傳: 執行結果</param>
        /// <param name="msg">回傳: 訊息</param>
        /// <returns>串流資訊</returns>
        public byte[] ExportResumeByDocx_ReplaceText(out bool result, out string msg)
        {
            result = true;
            msg    = "";
            MemoryStream ms = new MemoryStream();

            try
            {
                Spire.Doc.Document document = new Spire.Doc.Document();

                //載入套印檔
                //注意: 實際運作時,若同一時間有兩位以上使用者同時進行套印,會產生「無法開啟已開啟檔案」的錯誤
                //建議實作時,一個使用者執行匯出動作時先複製一個套印檔,完成套印後再將複製的檔案刪除,即可避開錯誤
                document.LoadFromFile(HttpContext.Current.Server.MapPath("~/App_Data/MyResumeSample.docx"));

                #region 定義樣式

                //定義樣式 BasicStyle: 一般段落文字
                ParagraphStyle style = new ParagraphStyle(document)
                {
                    Name = "Basic"
                };
                //style.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Justify;
                style.CharacterFormat.FontName = "標楷體";
                style.CharacterFormat.FontSize = 12;
                document.Styles.Add(style);

                #endregion

                //取得要套印的內容
                Resume model = new Resume();

                #region 套印內容

                document.Replace("{$Name$}", string.IsNullOrEmpty(model.Name) ? "" : model.Name, false, true);
                document.Replace("{$Gender$}", string.IsNullOrEmpty(model.Gender) ? "" : model.Gender, false, true);
                document.Replace("{$Email$}", string.IsNullOrEmpty(model.Email) ? "" : model.Email, false, true);
                document.Replace("{$Address$}", string.IsNullOrEmpty(model.Address) ? "" : model.Address, false, true);
                document.Replace("{$Phone$}", string.IsNullOrEmpty(model.Phone) ? "" : model.Phone, false, true);
                document.Replace("{$Mobile$}", string.IsNullOrEmpty(model.Mobile) ? "" : model.Mobile, false, true);

                //包含 HTML 字串需放置在 paragraph 內,
                //因此套印檔中的 {$Description1$} 及 {$Description2$} 需透過「以 paragraph 取代文字」方式替代
                //Replace {$Description1$} with paragraph
                TextSelection selection = document.FindString("{$Description1$}", false, true);
                TextRange     range     = selection.GetAsOneRange();
                Spire.Doc.Documents.Paragraph paragraph = range.OwnerParagraph;
                paragraph.ApplyStyle("Basic");
                paragraph.Replace("{$Description1$}", "", false, false);
                paragraph.AppendHTML(string.IsNullOrEmpty(model.Description1) ? "" : HttpUtility.HtmlDecode(model.Description1));

                //Replace {$Description2$} with paragraph
                selection = document.FindString("{$Description2$}", false, true);
                range     = selection.GetAsOneRange();
                paragraph = range.OwnerParagraph;
                paragraph.ApplyStyle("Basic");
                paragraph.Replace("{$Description2$}", "", false, false);
                paragraph.AppendHTML(string.IsNullOrEmpty(model.Description2) ? "" : HttpUtility.HtmlDecode(model.Description2));

                //Replace {$Img$} with Image
                DocPicture pic = new DocPicture(document);
                pic.LoadImage(Image.FromFile(HttpContext.Current.Server.MapPath("~/App_Data/Penguins.jpg")));

                selection = document.FindString("{$Img$}", false, true);
                range     = selection.GetAsOneRange();
                range.OwnerParagraph.ChildObjects.Insert(0, pic);
                range.OwnerParagraph.ChildObjects.Remove(range);

                #endregion

                #region 動態新增表格

                if (model.JobHistory.Count > 0)
                {
                    Spire.Doc.Section s      = document.AddSection();
                    Spire.Doc.Table   table  = s.AddTable(true);
                    string[]          Header = { "序號", "任職公司", "職稱", "開始時間", "結束時間" };

                    //Add Cells
                    table.ResetCells(model.JobHistory.Count + 1, Header.Length);

                    //Header Row
                    TableRow FRow = table.Rows[0];
                    FRow.IsHeader = true;
                    for (int i = 0; i < Header.Length; i++)
                    {
                        Spire.Doc.Documents.Paragraph p = FRow.Cells[i].AddParagraph();
                        FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        p.Format.HorizontalAlignment = HorizontalAlignment.Center;

                        TextRange TR = p.AppendText(Header[i]);
                        TR.CharacterFormat.Bold = true;
                    }

                    //Data Row
                    model.JobHistory = model.JobHistory.OrderBy(x => x.StartDT).ToList();
                    for (int r = 0; r < model.JobHistory.Count; r++)
                    {
                        TableRow DataRow = table.Rows[r + 1];
                        string[] data    = new string[] { (r + 1).ToString(), model.JobHistory[r].CompanyName, model.JobHistory[r].JobTitle, (model.JobHistory[r].StartDT.HasValue ? model.JobHistory[r].StartDT.Value.ToShortDateString() : ""), (model.JobHistory[r].EndDT.HasValue ? model.JobHistory[r].EndDT.Value.ToShortDateString() : "") };

                        //Columns.
                        for (int c = 0; c < data.Length; c++)
                        {
                            //Cell Alignment
                            DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

                            //Fill Data in Rows
                            Spire.Doc.Documents.Paragraph p2 = DataRow.Cells[c].AddParagraph();
                            TextRange TR2 = p2.AppendText(data[c]);

                            //Format Cells
                            p2.Format.HorizontalAlignment = HorizontalAlignment.Center;
                        }
                    }

                    //Replace text with Table
                    TextSelection selectionTable = document.FindString("{$JobHistory$}", true, true);
                    TextRange     rangeTable     = selectionTable.GetAsOneRange();
                    Spire.Doc.Documents.Paragraph paragraphTable = rangeTable.OwnerParagraph;
                    Body body  = paragraphTable.OwnerTextBody;
                    int  index = body.ChildObjects.IndexOf(paragraphTable);
                    body.ChildObjects.Remove(paragraphTable);
                    body.ChildObjects.Insert(index, table);
                }

                #endregion

                #region 套用樣式

                //套用文章段落樣式
                for (int s = 0; s < document.Sections.Count; s++)
                {
                    Spire.Doc.Section section = document.Sections[s];
                    //套用文章段落樣式
                    for (int p = 0; p < section.Paragraphs.Count; p++)
                    {
                        Spire.Doc.Documents.Paragraph pgh = section.Paragraphs[p];
                        pgh.ApplyStyle("Basic");
                        pgh.Format.BeforeSpacing = 12;
                    }

                    //套用表格樣式
                    for (int t = 0; t < document.Sections[s].Tables.Count; t++)
                    {
                        Spire.Doc.Table table = (Spire.Doc.Table)document.Sections[s].Tables[t];
                        table.PreferredWidth            = new PreferredWidth(WidthType.Percentage, 100);
                        table.TableFormat.IsAutoResized = true;

                        //set table border
                        //table.TableFormat.Borders.Right.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Left.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Top.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Horizontal.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Vertical.BorderType = Spire.Doc.Documents.BorderStyle.Thick;

                        for (int tr = 0; tr < table.Rows.Count; tr++)
                        {
                            for (int td = 0; td < table.Rows[tr].Cells.Count; td++)
                            {
                                for (int t_ph = 0; t_ph < table.Rows[tr].Cells[td].Paragraphs.Count; t_ph++)
                                {
                                    table.Rows[tr].Cells[td].Paragraphs[t_ph].ApplyStyle("Basic");
                                }
                            }
                        }
                    }
                }

                #endregion

                //匯出
                document.SaveToStream(ms, FileFormat.Docx);
            }
            catch (Exception ex)
            {
                result = false;
                msg    = ex.Message;
            }

            if (result)
            {
                return(ms.ToArray());
            }
            else
            {
                return(null);
            }
        }