private void button1_Click(object sender, EventArgs e)
        {
            //Load the document
            string   input = @"..\..\..\..\..\..\Data\Bookmark.docx";
            Document doc   = new Document();

            doc.LoadFromFile(input);

            //Create an instance of BookmarksNavigator
            BookmarksNavigator bn = new BookmarksNavigator(doc);

            //Find a bookmark named Test
            bn.MoveToBookmark("Test", true, true);

            //Add a section
            Section section0 = doc.AddSection();

            //Add a paragraph for the section
            Paragraph paragraph = section0.AddParagraph();
            Image     image     = Image.FromFile(@"..\..\..\..\..\..\Data\Word.png");

            //Add a picture into the paragraph
            DocPicture picture = paragraph.AppendPicture(image);

            //Add the paragraph at the position of bookmark
            bn.InsertParagraph(paragraph);

            //Remove the section0
            doc.Sections.Remove(section0);

            //Save and launch document
            string output = "InsertImageAtBookmark.docx";

            doc.SaveToFile(output, FileFormat.Docx);
            Viewer(output);
        }
        public IActionResult Batchs(string command, string ids)
        {
            var          response       = ResponseModelFactory.CreateInstance;
            string       sWebRootFolder = _hostingEnvironment.WebRootPath + "\\UploadFiles\\ImportUserInfoWord\\";
            var          timeInfo       = DateTime.Now.ToString("yyyyMMddHHmmss");
            var          wordName       = timeInfo + "address.docx";
            string       wordUrl        = sWebRootFolder + wordName;
            MemoryStream ms             = new MemoryStream();
            XWPFDocument m_Docx         = new XWPFDocument();

            m_Docx.Write(ms);
            ms.Flush();
            SaveToFile(ms, wordUrl);
            List <string> list = new List <string>();


            using (_dbContext)
            {
                //document111.LoadFromFile(sWebRootFolder + "test.docx");
                Document document111 = new Document();
                document111.LoadFromFile(wordUrl);
                Section section = document111.Sections[0];
                document111.Watermark = null;
                section.Paragraphs[0].AppendBookmarkStart("picture");
                section.Paragraphs[0].AppendBookmarkEnd("picture");
                var parameters     = ids.Split(",").Select((id, index) => new SqlParameter(string.Format("@p{0}", index), id)).ToList();
                var parameterNames = string.Join(", ", parameters.Select(p => p.ParameterName));
                var entities       = _dbContext.GrabageRoom.Where(x => ids.IndexOf(x.GarbageRoomUuid.ToString()) >= 0).ToList();
                for (int i = 0; i < entities.Count; i++)
                {
                    var pata = _hostingEnvironment.WebRootPath + EWM.GetEWM2("d_" + entities[i].GarbageRoomUuid.ToString(), _hostingEnvironment, entities[i].Ljname);
                    //实例化BookmarksNavigator类,指定需要添加图片的书签“”
                    BookmarksNavigator bn = new BookmarksNavigator(document111);
                    bn.MoveToBookmark("picture", true, true);
                    //添加段落,加载图片并插入到段落
                    Section section0 = document111.AddSection();
                    Spire.Doc.Documents.Paragraph paragraph = section0.AddParagraph();
                    Image image = Image.FromFile(pata);

                    //DocPicture picture = paragraph.AppendPicture(image);
                    DocPicture picture = document111.Sections[0].Paragraphs[0].AppendPicture(image);
                    picture.Width  = 160;
                    picture.Height = 180;
                    //picture.HorizontalPosition = 100.0f;
                    //picture.VerticalPosition = 100.0f;
                    bn.InsertParagraph(paragraph);
                    document111.Sections.Remove(section0);
                    //string output = sWebRootFolder + "test.docx";
                    document111.SaveToFile(wordUrl, FileFormat.Docx);
                }
                list.Add(wordUrl);
                //关闭进程
                document111.Dispose();
                var time  = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                var check = ZIP.CompressMulti(list, _hostingEnvironment.WebRootPath + "\\UploadFiles\\EWM\\" + time, false);
                if (check)
                {
                    response.SetSuccess("导出成功");
                    response.SetData("\\UploadFiles\\EWM\\" + time + ".zip");
                }
                else
                {
                    response.SetFailed("导出失败");
                }
                return(Ok(response));
            }
        }
예제 #3
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);
            }
        }
예제 #4
0
        private void GenerateButton_Click(object sender, RoutedEventArgs e)
        {
            string currentDir = Environment.CurrentDirectory;

            Document doc = new Document(currentDir + "\\template.docx", FileFormat.Docx);

            BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);

            bookmarkNavigator.MoveToBookmark("Name");
            bookmarkNavigator.ReplaceBookmarkContent(CVName.Text, true);

            bookmarkNavigator.MoveToBookmark("Position");
            bookmarkNavigator.ReplaceBookmarkContent(CVPositionResult.Text, true);

            bookmarkNavigator.MoveToBookmark("Summary");
            bookmarkNavigator.ReplaceBookmarkContent(CVSummaryResult.Text, true);

            bookmarkNavigator.MoveToBookmark("Languages");
            bookmarkNavigator.ReplaceBookmarkContent(CVLangualeResult.Text, true);

            bookmarkNavigator.MoveToBookmark("Databases");
            bookmarkNavigator.ReplaceBookmarkContent(CVDatabasesResult.Text, true);

            bookmarkNavigator.MoveToBookmark("Technologies");
            bookmarkNavigator.ReplaceBookmarkContent(CVTechnologyResult.Text, true);

            bookmarkNavigator.MoveToBookmark("Tools");
            bookmarkNavigator.ReplaceBookmarkContent(CVToolsResult.Text, true);

            bookmarkNavigator.MoveToBookmark("Langs");
            bookmarkNavigator.ReplaceBookmarkContent(CVNonPrLangualeResult.Text, true);

            string Experience = "";

            foreach (ListBoxItem c in CVExperienceResult.Items)
            {
                Experience += c.Content + "\n";
            }

            bookmarkNavigator.MoveToBookmark("Projects");
            bookmarkNavigator.ReplaceBookmarkContent(Experience, true);

            string Education = "";

            foreach (ListBoxItem c in CVEducationResult.Items)
            {
                Education += c.Content + "\n";
            }

            bookmarkNavigator.MoveToBookmark("Education");
            bookmarkNavigator.ReplaceBookmarkContent(Education, true);

            bookmarkNavigator.MoveToBookmark("Image");

            Paragraph p = new Paragraph(doc);

            if (image != null)
            {
                DocPicture Pic = p.AppendPicture(imageBtm.StreamSource);

                bookmarkNavigator.ReplaceBookmarkContent("", true);
                bookmarkNavigator.InsertParagraph(p);

                Pic.Width  = 150;
                Pic.Height = 150;
            }

            doc.SaveToFile(currentDir + "\\" + CVName.Text + ".docx", FileFormat.Docx);
        }
        public IActionResult yjExportInfo(AddressRequestPayload payload)
        {
            var response = ResponseModelFactory.CreateInstance;

            string       sWebRootFolder = _hostingEnvironment.WebRootPath + "\\UploadFiles\\ImportUserInfoWord\\";
            var          timeInfo       = DateTime.Now.ToString("yyyyMMddHHmmss");
            var          wordName       = timeInfo + "address.docx";
            string       wordUrl        = sWebRootFolder + wordName;
            MemoryStream ms             = new MemoryStream();
            XWPFDocument m_Docx         = new XWPFDocument();

            m_Docx.Write(ms);
            ms.Flush();
            SaveToFile(ms, wordUrl);

            List <string> list = new List <string>();

            using (_dbContext)
            {
                Document document111 = new Document();
                document111.LoadFromFile(wordUrl);
                Section section = document111.Sections[0];
                section.Paragraphs[0].AppendBookmarkStart("picture");
                section.Paragraphs[0].AppendBookmarkEnd("picture");

                var      user = AuthContextService.CurrentUser;
                string   s1   = payload.Kw2;
                string[] s2   = s1.Split(" ");
                StringBuilder where = new StringBuilder();
                StringBuilder sql = new StringBuilder("SELECT * FROM HomeAddress HA ");
                for (int i = 0; i < s2.Length; i++)
                {
                    if (s2.Length > 0 && i == 0)
                    {
                        where.Append("WHERE ");
                    }
                    where.Append("HA.Address LIKE '%" + s2[i] + "%' ");
                    if (i >= 0 && i < s2.Length - 1)
                    {
                        where.Append(" AND ");
                    }
                }
                sql.Append(where);
                //var query = _dbContext.HomeAdd.FromSql(sql.ToString());
                var query = _dbContext.HomeAddress.FromSqlRaw(sql.ToString());
                if (!string.IsNullOrEmpty(payload.Kw))
                {
                    query = query.Where(x => x.Address.ToString().Contains(payload.Kw));
                }
                if (!string.IsNullOrEmpty(payload.Kw1))
                {
                    query = query.Where(x => x.Address.ToString().Contains(payload.Kw1));
                }
                var entities = query.ToList();
                //var entities = _dbContext.HomeAddress.Where(x => ids.IndexOf(x.HomeAddressUuid.ToString()) >= 0).ToList();
                for (int i = 0; i < entities.Count(); i++)
                {
                    var pata = _hostingEnvironment.WebRootPath + EWM.GetEWM2("h_" + entities[i].HomeAddressUuid.ToString(), _hostingEnvironment, entities[i].Address);
                    //实例化BookmarksNavigator类,指定需要添加图片的书签“”
                    BookmarksNavigator bn = new BookmarksNavigator(document111);
                    bn.MoveToBookmark("picture", true, true);
                    //添加段落,加载图片并插入到段落
                    Section section0 = document111.AddSection();
                    Spire.Doc.Documents.Paragraph paragraph = section0.AddParagraph();
                    Image      image   = Image.FromFile(pata);
                    DocPicture picture = document111.Sections[0].Paragraphs[0].AppendPicture(image);
                    picture.Width  = 160;
                    picture.Height = 180;
                    //picture.HorizontalPosition = 100.0f;
                    //picture.VerticalPosition = 50.0f;
                    bn.InsertParagraph(paragraph);
                    document111.Sections.Remove(section0);
                    //string output = sWebRootFolder + "test.docx";
                    document111.SaveToFile(wordUrl, FileFormat.Docx);
                    //Arraypata = pata.;
                    //list.Add(pata);
                }
                list.Add(wordUrl);
                //关闭进程
                document111.Dispose();
                var time  = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                var check = ZIP.CompressMulti(list, _hostingEnvironment.WebRootPath + "\\UploadFiles\\EWM\\" + time, false);
                if (check)
                {
                    response.SetSuccess("导出成功");
                    response.SetData("\\UploadFiles\\EWM\\" + time + ".zip");
                }
                else
                {
                    response.SetFailed("导出失败");
                }
            }
            return(Ok(response));
        }