Beispiel #1
0
        private void PdfExtractWordAndPicture(string savePathCache, string midName)//参数:保存地址,处理过程中文件名称(不包含后缀)
        {
            #region   提取PDF中的文字

            try
            {
                PdfDocument doc = new PdfDocument();
                doc.LoadFromFile(savePathCache + "\\" + midName + ".pdf");      //加载文件
                StringBuilder content = new StringBuilder();
                foreach (PdfPageBase page in doc.Pages)
                {
                    content.Append(page.ExtractText());
                }


                System.IO.File.WriteAllText(savePathCache + "\\mid.txt", content.ToString());

                Spire.Doc.Document document = new Spire.Doc.Document();
                document.LoadFromFile(savePathCache + "\\mid.txt");
                document.Replace(" ", "", true, true);
                document.Replace("Evaluation Warning : The document was created with Spire.PDF for .NET.", "", true, true);
                document.SaveToFile(savePathCache + "\\" + midName + ".doc", Spire.Doc.FileFormat.Doc);

                File.Delete(savePathCache + "\\mid.txt");
            }
            catch (Exception)
            {
                MessageBox.Show("请填写正确的路径");
            }
            #endregion

            #region  提取PDF中的图片
            //创建一个PdfDocument类对象并加载PDF sample
            Spire.Pdf.PdfDocument mydoc = new Spire.Pdf.PdfDocument();
            mydoc.LoadFromFile(savePathCache + "\\" + midName + ".pdf");

            //声明一个IList类,元素为image
            IList <Image> images = new List <Image>();
            //遍历PDF文档中诊断是否包含图片,并提取图片
            foreach (PdfPageBase page in mydoc.Pages)
            {
                if (page.ExtractImages() != null)
                {
                    foreach (Image image in page.ExtractImages())
                    {
                        images.Add(image);
                    }
                }
            }
            mydoc.Close();

            //遍历提取的图片,保存并命名图片
            int index = 0;
            foreach (Image image in images)
            {
                String imageFileName = String.Format(midName + "Image-{0}.png", index++);
                image.Save(savePathCache + "\\" + imageFileName, ImageFormat.Png);
            }
            #endregion
        }
Beispiel #2
0
        /// <summary>
        /// 添加尾注
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="str"></param>
        public void AddWeizhu(string filename, string str)
        {
            //获得数据库中str对应的来源
            string str_sql = $"select 来源 from {Setting._cijuchachongbiao} where 内容='{Hulue(str.Trim())}'";
            Dictionary <string, object> dic = mysqliter.ExecuteRow(str_sql, null, null)[0] as Dictionary <string, object>;
            string laiyuan = dic["来源"].ToString();

            Spire.Doc.Document mydoc = new Spire.Doc.Document();
            mydoc.LoadFromFile(filename);
            TextSelection[] texts = mydoc.FindAllString(str, false, true);
            if (texts == null)
            {
                return;
            }
            //给所有查找到的文字添加脚注
            foreach (TextSelection item in texts)
            {
                //实例化一个脚注的同时,直接创建在指定textselection所在的段落
                Spire.Doc.Fields.Footnote footnote = item.GetAsOneRange().OwnerParagraph.AppendFootnote(Spire.Doc.FootnoteType.Endnote);
                //向脚注内添加文字
                footnote.TextBody.AddParagraph().AppendText(laiyuan);
                //获得这个自然段
                Spire.Doc.Documents.Paragraph mypara = item.GetAsOneRange().OwnerParagraph;
                //向这个段落内的子节点添加脚注
                mypara.ChildObjects.Insert(mypara.ChildObjects.IndexOf(item.GetAsOneRange()) + 1, footnote);
            }
            mydoc.SaveToFile(filename);
            mydoc.Dispose();
            //去水印
            ClearShuiyin(filename);
        }
Beispiel #3
0
        public void AddWeizhu(string filename, string str)
        {
            Dictionary <string, object> dic = new Dictionary <string, object> {
                { "内容", this.Hulue(str.Trim()) }
            };
            var    list = _sqlhelper.GetAnySet(Setting._cijuchachongbiao, dic);
            string text = list[0]["来源"].ToString();

            Spire.Doc.Document document = new Spire.Doc.Document();
            document.LoadFromFile(filename);
            TextSelection[] selectionArray = document.FindAllString(str, false, true);
            if (selectionArray != null)
            {
                TextSelection[] selectionArray2 = selectionArray;
                int             index           = 0;
                while (true)
                {
                    if (index >= selectionArray2.Length)
                    {
                        document.SaveToFile(filename);
                        document.Dispose();
                        this.ClearShuiyin(filename);
                        break;
                    }
                    TextSelection             selection = selectionArray2[index];
                    Spire.Doc.Fields.Footnote entity    = selection.GetAsOneRange().OwnerParagraph.AppendFootnote(Spire.Doc.FootnoteType.Endnote);
                    entity.TextBody.AddParagraph().AppendText(text);
                    Paragraph ownerParagraph = selection.GetAsOneRange().OwnerParagraph;
                    ownerParagraph.ChildObjects.Insert(ownerParagraph.ChildObjects.IndexOf(selection.GetAsOneRange()) + 1, entity);
                    index++;
                }
            }
        }
        // Cохранение файла DOC
        private void LoadDoc_Click(object sender, RoutedEventArgs e)
        {
            Spire.Doc.Document document = new Spire.Doc.Document();
            document.LoadFromFile(pathDOC);
            document.SaveToFile("ScheduleByCorrespondence.HTML", Spire.Doc.FileFormat.Html);

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://212.86.101.101/ScheduleByCorrespondence.html");

            request.Method      = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential("anonymous", "");
            byte[] fileContents;
            using (StreamReader sourceStream = new StreamReader(pathDOC))
            {
                fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            }

            request.ContentLength = fileContents.Length;

            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(fileContents, 0, fileContents.Length);
            }

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                Message.Content = ($"Upload File Complete, status {response.StatusDescription}");
            }
        }
Beispiel #5
0
        private void button1_Click(object sender, EventArgs e)
        {
            #region   将pdf分成许多份小文档
            Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();
            pdf.LoadFromFile(textBox1.Text);
            label4.Text = "转换中......";
            label4.Refresh();
            for (int i = 0; i < pdf.Pages.Count; i += 5)
            {
                int j = 0;
                Spire.Pdf.PdfDocument newpdf = new Spire.Pdf.PdfDocument();
                for (j = i; j >= i && j <= i + 4; j++)
                {
                    if (j < pdf.Pages.Count)
                    {
                        Spire.Pdf.PdfPageBase page;
                        page = newpdf.Pages.Add(pdf.Pages[j].Size, new Spire.Pdf.Graphics.PdfMargins(0));
                        pdf.Pages[j].CreateTemplate().Draw(page, new PointF(0, 0));
                    }
                }
                newpdf.SaveToFile(textBox2.Text + "\\" + j.ToString() + ".pdf");
                PdfExtractWordAndPicture(textBox2.Text, j.ToString());
            }
            #endregion


            #region  合并word文档

            string filePath0 = textBox2.Text + "\\" + '5' + ".doc";
            for (int i = 10; i <= 0 - pdf.Pages.Count % 5 + pdf.Pages.Count; i += 5)
            {
                string filePath2 = textBox2.Text + "\\" + i.ToString() + ".doc";

                Spire.Doc.Document doc = new Spire.Doc.Document(filePath0);
                doc.InsertTextFromFile(filePath2, Spire.Doc.FileFormat.Doc);

                doc.SaveToFile(filePath0, Spire.Doc.FileFormat.Doc);
            }
            Spire.Doc.Document mydoc1 = new Spire.Doc.Document();
            mydoc1.LoadFromFile(textBox2.Text + "\\" + '5' + ".doc");
            mydoc1.SaveToFile(textBox2.Text + "\\" + "TheLastTransform" + ".doc", Spire.Doc.FileFormat.Doc);

            for (int i = 5; i <= 5 - pdf.Pages.Count % 5 + pdf.Pages.Count; i += 5)
            {
                File.Delete(textBox2.Text + "\\" + i.ToString() + ".doc");
                File.Delete(textBox2.Text + "\\" + i.ToString() + ".pdf");
            }

            #endregion

            label4.Text = "转换完成";
            label4.Refresh();
        }
Beispiel #6
0
        private void button5_Click(object sender, EventArgs e)
        {
            Spire.Doc.Document doc1 = new Spire.Doc.Document();

            doc1.LoadFromFile(@"C:\Downloads\Tax_Header_Document.docx");
            Spire.Doc.HeaderFooter header = doc1.Sections[0].HeadersFooters.Header;
            Spire.Doc.Document     doc2   = new Spire.Doc.Document(@"C:\Downloads\2301-233608- Tax Cert.docx");
            foreach (Spire.Doc.Section section in doc2.Sections)
            {
                foreach (DocumentObject obj in header.ChildObjects)
                {
                    section.HeadersFooters.Header.ChildObjects.Add(obj.Clone());
                }
            }
            //doc2.SaveToFile(@"C:\Downloads\TAx_Final.docx", Spire.Doc.FileFormat.Docx);
        }
Beispiel #7
0
        public void CleanFile()
        {
            //Instantiate a Document object
            Spire.Doc.Document document = new Spire.Doc.Document();
            //Load the Word document
            document.LoadFromFile(@"C:\Users\Konstantin\Desktop\WSIiZ\QRCodeSample\QRCodeSample\QR.docx");

            //Remove paragraphs from every section in the document
            foreach (Spire.Doc.Section section in document.Sections)
            {
                section.Paragraphs.Clear();
            }

            //Save the document
            document.SaveToFile(@"C:\Users\Konstantin\Desktop\WSIiZ\QRCodeSample\QRCodeSample\QR.docx", FileFormat.Docx2013);
        }
Beispiel #8
0
        private static StringBuilder WordToText(string fullName)
        {
            Spire.Doc.Document doc = new Spire.Doc.Document();
            doc.LoadFromFile(fullName);

            // Initilize StringBuilder Instance
            StringBuilder toText = new StringBuilder();

            //Extract Text from Word and Save to StringBuilder Instance
            foreach (Section section in doc.Sections)
            {
                foreach (SDocuments.Paragraph paragraph in section.Paragraphs)
                {
                    toText.AppendLine(paragraph.Text);
                }
            }
            return(toText);
        }
Beispiel #9
0
        static void Ziple()
        {
            string inputPath = "C:/Users/Administrator/Desktop/metinDeneme.docx";


            Spire.Doc.Document document = new Spire.Doc.Document();
            document.LoadFromFile(inputPath);

            //Convert Word to PDF
            document.SaveToFile("metin.PDF", FileFormat.PDF);
            byte[] array = File.ReadAllBytes("metin.PDF");

            webReferans.WebService1 ws = new webReferans.WebService1();
            byte[] zipByteArray        = ws.ZipThat("metin.pdf", array);
            File.WriteAllBytes("C:/Users/Administrator/Desktop/test.zip", zipByteArray);

            Console.WriteLine("İşlem Başarılı .");
            Console.ReadLine();
        }
        private void Finalizer(Content content)
        {
            using (var outputDocument = new TemplateProcessor(_outputPath)
                                        .SetRemoveContentControls(true))
            {
                outputDocument.FillContent(content);
                outputDocument.SaveChanges();
            }


            Document document = new Document();

            document.LoadFromFile(_outputPath);

            //Convert Word to PDF
            document.SaveToFile("toPDF.PDF", FileFormat.PDF);


            //Launch Document
            Process.Start("toPDF.PDF");
        }
Beispiel #11
0
        static void MultiZiple()
        {
            string inputPath1 = "C:/Users/Administrator/Desktop/metinDeneme.docx";
            string inputPath2 = "C:/Users/Administrator/Desktop/metinDeneme2.docx";

            Spire.Doc.Document doc1 = new Spire.Doc.Document();
            Spire.Doc.Document doc2 = new Spire.Doc.Document();

            doc1.LoadFromFile(inputPath1);
            doc2.LoadFromFile(inputPath2);

            doc1.SaveToFile("metin1.PDF", FileFormat.PDF);
            doc2.SaveToFile("metin2.PDF", FileFormat.PDF);

            byte[] metin1_Array = File.ReadAllBytes("metin1.PDF");
            byte[] metin2_Array = File.ReadAllBytes("metin2.PDF");

            webReferans.WebService1 ws = new webReferans.WebService1();

            byte[] multiZipArray = ws.ZipMulti("metin1.PDF", "metin2.PDF", metin1_Array, metin2_Array);

            File.WriteAllBytes("C:/Users/Administrator/Desktop/testMultiZip.zip", multiZipArray);
        }
Beispiel #12
0
        public ActionResult Download(RegisterExternalLoginModel mReg, string Command, int id = 0)
        {
            if (Command == "MS Word")
            {
                try
                {
                    var userGuid = new Guid(User.Identity.GetUserId()); //WebSecurity.GetUserId(User.Identity.Name);
                    var userId   = BitConverter.ToInt32(userGuid.ToByteArray(), 0);

                    var responses  = _db.Responses.Where(x => x.UserId == userId).OrderBy(x => x.Ordinal).ThenBy(x => x.SubOrdinal).ThenBy(x => x.QQOrd).ToList();
                    var categories = new List <string> {
                        "Personal Information", "Employment", "Education", "Coursework", "Certifications", "Licenses", "Credentials", "Training"
                    };
                    var fui       = new FormatUserInformation(responses, categories);
                    var formatted = fui.Format();
                    var ms        = MakeWordFile.CreateDocument(formatted);
                    var ms2       = new MemoryStream(ms.ToArray());


                    Spire.Doc.Document doc = new Spire.Doc.Document(ms2);

                    doc.SaveToFile("Portfolio.docx", Spire.Doc.FileFormat.Docx, System.Web.HttpContext.Current.Response, HttpContentType.Attachment);

                    //Response.Clear();
                    //Response.AddHeader("content-disposition", "attachment; filename=\"Portfolio.docx\"");
                    //Response.ContentType = "application/msword";
                    //ms2.WriteTo(Response.OutputStream);
                    //Response.End();
                }
                catch (Exception ex)
                { Response.Write(ex.Message); }
            }
            else if (Command == "Pdf")
            {
                try
                {
                    var userGuid = new Guid(User.Identity.GetUserId()); //WebSecurity.GetUserId(User.Identity.Name);
                    var userId   = BitConverter.ToInt32(userGuid.ToByteArray(), 0);

                    var responses  = _db.Responses.Where(x => x.UserId == userId).OrderBy(x => x.Ordinal).ThenBy(x => x.SubOrdinal).ThenBy(x => x.QQOrd).ToList();
                    var categories = new List <string> {
                        "Personal Information", "Employment", "Education", "Coursework", "Certifications", "Licenses", "Credentials", "Training"
                    };
                    var fui       = new FormatUserInformation(responses, categories);
                    var formatted = fui.Format();
                    var ms        = MakeWordFile.CreateDocument(formatted);
                    var ms2       = new MemoryStream(ms.ToArray());

                    Spire.Doc.Document doc = new Spire.Doc.Document(ms2);

                    doc.SaveToFile("Portfolio.pdf", Spire.Doc.FileFormat.PDF, System.Web.HttpContext.Current.Response, HttpContentType.Attachment);
                }
                catch (Exception ex)
                { Response.Write(ex.Message); }
            }
            else if (Command == "Certificate")
            {
                var userGuid  = new Guid(User.Identity.GetUserId());
                var userIdStr = User.Identity.GetUserId();
                var userId    = BitConverter.ToInt32(userGuid.ToByteArray(), 0);
                var user      = _udb.Users.FirstOrDefault(s => s.Id == userIdStr);

                UserLevel userLevel        = _db.UserLevels.Where(q => q.UserId == userId).First();
                var       certificateDate  = ((DateTime)userLevel.FinalStepLevelDate).ToString("d");
                var       certificateLevel = userLevel.FinalStepLevel;
                var       signature        = "Zelda Boyd";

                string firstName     = "";
                string lastName      = "";
                string middleInitial = "";

                if (user != null)
                {
                    if (user.FirstName != null && user.FirstName != "")
                    {
                        firstName = user.FirstName;
                    }
                    else
                    {
                        firstName = "FirstName";
                    }

                    if (user.LastName != null && user.LastName != "")
                    {
                        lastName = user.LastName;
                    }
                    else
                    {
                        lastName = "LastName";
                    }

                    if (user.MiddleInitial != null && user.MiddleInitial != "")
                    {
                        middleInitial = user.MiddleInitial;
                    }
                    else
                    {
                        middleInitial = "";
                    }
                }

                firstName     = user.FirstName;
                middleInitial = user.MiddleInitial;
                lastName      = user.LastName;

                string fullName = firstName + " " + (middleInitial != "" ? middleInitial + " " : "") + lastName;

                var appRoot = Request.PhysicalApplicationPath;
                var file    = appRoot + "Content\\VPDR_Certificate_10.docx";
                var newFile = appRoot + "Content\\VPDR_Certificate_" + lastName + "_" + firstName + ".docx";
                var newPdf  = appRoot + "Content\\VPDR_Certificate_" + lastName + "_" + firstName + ".pdf";

                Spire.Doc.Document doc = new Spire.Doc.Document();
                doc.LoadFromFile(file);
                doc.Replace("PROVIDER", fullName, true, true);
                doc.Replace("LEVEL", certificateLevel, true, true);
                doc.Replace("DATE", certificateDate, true, true);
                doc.Replace("SIGNATURE", signature, true, true);
                //doc.SaveToFile(newPdf, Spire.Doc.FileFormat.PDF);
                //doc.SaveToFile(newFile, Spire.Doc.FileFormat.Docx);

                var newPdfName = "VPDR_Certificate_" + lastName + "_" + firstName + ".pdf";
                doc.SaveToFile(newPdfName, Spire.Doc.FileFormat.PDF, System.Web.HttpContext.Current.Response, HttpContentType.Attachment);
            }

            if (ModelState.IsValid)
            {
                return(RedirectToAction("Index"));
            }

            return(RedirectToAction("Download"));
        }
        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));
            }
        }
Beispiel #14
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);
            }
        }
        private void CreateDocument(object o)
        {
            ExcelInfo ei = o as ExcelInfo;

            dgv_task.Rows[ei._id - 1].Cells[4].Value = "正在准备";
            //获得 table
            DataTable dt_split = ei._data;

            //读取excel,得到行数
            /*生成一个新的word*/
            Spire.Doc.Document spdoc = new Spire.Doc.Document();
            /*循环把list中的mycu内容添加到word文档*/
            for (int rowindex = 0; rowindex < dt_split.Rows.Count; rowindex++)
            {
                dgv_task.Rows[ei._id - 1].Cells[4].Value = (100 * Convert.ToDecimal(rowindex + 1) / Convert.ToDecimal(dt_split.Rows.Count)).ToString("00.00") + "%";
                //更新状态栏文字
                //string str_statue = "正在生成第{0}个,共{1}个……";
                //UpdateStatue(string.Format(str_statue, rowindex - 1, lastrow - 1));
                ///载入一个空白文档
                spdoc.LoadFromFile(Environment.CurrentDirectory + @"\newdoc.docx");
                for (int i = Global.list_myuc.Count - 1; i >= 0; i--)
                {
                    //设置文本
                    string str_n = string.Empty;
                    //设置空行
                    for (int ji = 0; ji < Global.list_myuc[i].mysetter.konghang; ji++)
                    {
                        str_n += "\n";
                    }
                    //添加一个段落

                    Spire.Doc.Documents.Paragraph parainsert = spdoc.LastSection.AddParagraph();
                    //Spire.Doc.Documents.Paragraph parainsert = spdoc.CreateParagraph();
                    TextRange tx = parainsert.AppendText(GetContent(Global.list_myuc[i].mysetter.listcolumn, rowindex, dt_split) + str_n);
                    //字体名称
                    tx.CharacterFormat.FontName = Global.list_myuc[i].mysetter.fontname;
                    //字体大小
                    tx.CharacterFormat.FontSize = Global.list_myuc[i].mysetter.fontsize;
                    //设置行距
                    switch (Global.list_myuc[i].mysetter.hangjustyle)
                    {
                    case "单倍行距":
                        parainsert.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.AtLeast;
                        break;

                    case "1.5倍行距":
                        parainsert.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.Exactly;
                        break;

                    case "2倍行距":
                        parainsert.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.Multiple;
                        break;

                    default:
                        parainsert.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.Exactly;
                        parainsert.Format.LineSpacing     = Global.list_myuc[i].mysetter.hangjuvalue;
                        break;
                    }
                    //首行缩进
                    parainsert.Format.SetFirstLineIndent(Global.list_myuc[i].mysetter.suojin); //首行缩进
                                                                                               //粗体
                    tx.CharacterFormat.Bold = Global.list_myuc[i].mysetter.bold == 1 ? true : false;
                    switch (Global.list_myuc[i].mysetter.juzhong)
                    {
                    case "左对齐":
                        parainsert.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left;
                        break;

                    case "居中":
                        parainsert.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                        break;

                    case "右对齐":
                        parainsert.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right;
                        break;
                    }
                }

                SectionCollection sections = spdoc.Sections;
                //创建一个HeaderFooter类实例,添加页脚
                for (int i = 0; i < sections.Count; i++)
                {
                    sections[i].PageSetup.Margins.Top    = 72f;
                    sections[i].PageSetup.Margins.Left   = 90f;
                    sections[i].PageSetup.Margins.Bottom = 72f;
                    sections[i].PageSetup.Margins.Right  = 90f;
                    Spire.Doc.HeaderFooter        footer     = sections[i].HeadersFooters.Footer;
                    Spire.Doc.Documents.Paragraph footerPara = footer.AddParagraph();

                    //添加字段类型为页码,添加当前页、分隔线以及总页数
                    footerPara.AppendField("页码", FieldType.FieldPage);
                    footerPara.AppendText(" / ");
                    footerPara.AppendField("总页数", FieldType.FieldNumPages);
                    footerPara.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                }
                /*保存文档*/
                //组成文件名
                List <string> strfilename = new List <string>();
                for (int i = 0; i < Global.listfilename.Count; i++)
                {
                    string filename_element = Regex.Replace(dt_split.Rows[rowindex][Global.listfilename[i] + 1].ToString(), @"[\s/\:*?''<>|]", "");
                    strfilename.Add(filename_element);
                }
                spdoc.BuiltinDocumentProperties.Author = "潜挖智库";
                spdoc.SaveToFile(tbcunfang.Text + @"\" + string.Join("-", strfilename) + @".docx");
                spdoc.Close();
            }
        }
Beispiel #16
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);
            }
        }
Beispiel #17
0
        private void button1_Click(object sender, EventArgs e)
        {
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("pl-PL");
            using (DocX document = DocX.Load(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój1.docx"))
            {
                // Check if all the replace patterns are used in the loaded document.


                document.ReplaceText("@PrzykładowyTekstDoZmiany0", "PierwszaWstawkaBezSPacji_Znakmi!#$%^)&()", false, System.Text.RegularExpressions.RegexOptions.None, new Formatting()
                {
                    Bold = true
                });
                document.ReplaceText("@PrzykładowyTekstDoZmiany1", "Zwykły tekst ", false, System.Text.RegularExpressions.RegexOptions.None, new Formatting()
                {
                    Bold = true
                });
                document.ReplaceText("@PrzykładowyTekstDoZmiany2", "Zwykły tekst, dodany przez aplikację (      )   ", false, System.Text.RegularExpressions.RegexOptions.None, new Formatting()
                {
                    Bold = true
                });

                var p = document.InsertParagraph();
                p.Append("Przykładowy czerwony tekst dodany na końcu,")
                .Font(new Font("Arial"))
                .FontSize(25)
                .Color(System.Drawing.Color.Red)
                .Bold()
                .Append(" zawierający dodatkowe inne niebieskie formatowanie").Font(new Font("Times New Roman")).Color(System.Drawing.Color.Blue).Italic()
                .SpacingAfter(40);
                // Save this document to disk.
                document.SaveAs(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.docx");



                using (DocX document1 = DocX.Load(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój1.docx"))
                {
                    using (DocX document3 = DocX.Load(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.docx"))
                    {
                        document1.InsertDocument(document3, true);
                        document1.SaveAs(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój3.docx");
                    }
                }


                var n      = DateTime.Now;
                var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second));
                tempDi.Create();

                /*
                 * This example loads each document into a byte array, then into a memory stream, so that the document can be opened for writing without
                 * modifying the source document.
                 */
                //foreach (var file in Directory.GetFiles("../../", "*.docx"))
                //{
                //    ConvertToHtml(file, tempDi.FullName);

                //}

                byte[] byteArray = File.ReadAllBytes(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.docx");
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    memoryStream.Write(byteArray, 0, byteArray.Length);
                    using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
                    {
                        HtmlConverterSettings settings = new HtmlConverterSettings()
                        {
                            PageTitle = "My Page Title"
                        };
                        XElement html = HtmlConverter.ConvertToHtml(doc, settings);

                        File.WriteAllText(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.html", html.ToStringNewLineOnAttributes());
                    }
                }

                string test = File.ReadAllText(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.hmtl");

                //Byte[] res = null;
                //using (MemoryStream ms = new MemoryStream())
                //{
                //    var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(test, PdfSharp.PageSize.A4);
                //    pdf.Save(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.pdf");
                //    res = ms.ToArray();
                //}


                //Load Document
                Spire.Doc.Document document2 = new Spire.Doc.Document();
                document2.LoadFromFile(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.docx");
                //Convert Word to PDF
                document2.SaveToFile("toPDF.PDF", FileFormat.PDF);
                //Launch Document
                System.Diagnostics.Process.Start("toPDF.PDF");


                string[]    pdfFiles          = { @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF" };
                PdfDocument outputPDFDocument = new PdfDocument();
                foreach (string pdfFile in pdfFiles)
                {
                    PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
                    outputPDFDocument.Version = inputPDFDocument.Version;
                    foreach (PdfPage page in inputPDFDocument.Pages)
                    {
                        outputPDFDocument.AddPage(page);
                    }
                }
                outputPDFDocument.Save(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF2.PDF");
            }
        }
        //파일에서 문자열 읽기
        private void FindFiles(object _sDir)
        {
            string sDir = _sDir as string;
            //string fileContents = null; //문서가 가지고 있는 내용
            List <string> idList = null; //파일별 발견된 주민등록번호들

            // Spire.Doc.Documents.TextSelection[] collectedId = null; //정규식에 의해 검색된 주민번호의 리스트.

            foreach (string filePath in Directory.GetFileSystemEntries(sDir, "*.*")
                     .Where(file => System.IO.Path.GetExtension(file).ToLower().Equals(".txt") ||
                            System.IO.Path.GetExtension(file).ToLower().Equals(".doc") ||
                            System.IO.Path.GetExtension(file).ToLower().Equals(".docx") ||
                            System.IO.Path.GetExtension(file).ToLower().Equals(".xls") ||
                            System.IO.Path.GetExtension(file).ToLower().Equals(".xlsx")))
            {
                // 크로스스레드 해결
                this.Invoke(new MethodInvoker(delegate()
                {
                    consoleTextBox.Text = filePath + " 읽는중..";
                }));

                try
                {
                    string plainText = "";
                    switch (System.IO.Path.GetExtension(filePath))
                    {
                    //TXT파일
                    case ".txt":
                        idList    = new List <string>();
                        plainText = File.ReadAllText(filePath);
                        plainText = plainText.Replace(" ", "");
                        foreach (Match s in Regex.Matches(plainText, patternHyphen))
                        {
                            if (isId(s.Value.ToString()))
                            {
                                idList.Add(s.ToString());
                            }
                        }
                        break;

                    //MS WORD 파일
                    case ".doc":
                    case ".docx":
                        if (System.IO.File.Exists("temp"))
                        {
                            System.IO.File.Delete("temp");
                        }
                        idList = new List <string>();
                        Spire.Doc.Document document = new Spire.Doc.Document();
                        document.LoadFromFile(filePath);
                        document.SaveToTxt("temp", Encoding.UTF8);
                        plainText = System.IO.File.ReadAllText("temp");
                        foreach (Match s in Regex.Matches(plainText, patternHyphen))
                        {
                            if (isId(s.Value.ToString()))
                            {
                                idList.Add(s.ToString());
                            }
                        }
                        //collectedId = document.FindAllPattern(new Regex(patternHyphen));
                        //foreach (Spire.Doc.Documents.TextSelection s in collectedId)
                        //{
                        //    if (isId(s.SelectedText.ToString()))
                        //    {
                        //        idList.Add(s.SelectedText.ToString());
                        //    }
                        //}
                        System.IO.File.Delete("temp");
                        break;

                    //MS EXCEL파일
                    case ".xls":
                    case ".xlsx":
                        plainText = "";
                        idList    = new List <string>();
                        Workbook workbook = new Workbook();

                        //엑셀파일오픈
                        workbook.LoadFromFile(filePath);

                        //각 워크시트별로 파싱
                        for (int i = 0; i < workbook.Worksheets.Count; i++)
                        {
                            Worksheet sheet = workbook.Worksheets[i];
                            if (!sheet.IsEmpty)
                            {
                                if (System.IO.File.Exists("temp"))
                                {
                                    System.IO.File.Delete("temp");
                                }

                                //전체 text 읽기 불가. txt파일 저장 후 파싱
                                sheet.SaveToFile("temp", "|", Encoding.UTF8);
                                plainText += System.IO.File.ReadAllText("temp");
                                plainText += "\r\n";
                            }
                        }
                        plainText = plainText.Replace(" ", "");     //공백제거
                        foreach (Match s in Regex.Matches(plainText, patternHyphen))
                        {
                            if (isId(s.Value.ToString()))
                            {
                                idList.Add(s.ToString());
                            }
                        }
                        System.IO.File.Delete("temp");
                        break;
                    }
                }
                catch
                {
                }

                //발견된 파일이 있으면 리스트에 등록
                if (idList.Count != 0)
                {
                    filesPathAndIdList.Add(new FilesPathAndID(filePath, idList));
                }
            }

            //재귀적으로 디렉토리 탐색
            if ((File.GetAttributes(sDir) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
            {
                foreach (string d in Directory.GetDirectories(sDir))
                {
                    try
                    {
                        FindFiles(d);
                    }
                    catch
                    {
                    }
                }
            }
        }
Beispiel #19
0
        private void Button4_Click(object sender, EventArgs e)
        {
            DataTable dt                   = (DataTable)dataGridView1.DataSource;
            bool      IsExistEmail         = false;
            bool      IsExistcontactperson = false;

            foreach (DataColumn col in dt.Columns)
            {
                if (col.ColumnName == "EMAIL")
                {
                    IsExistEmail = true;
                }
            }
            foreach (DataColumn col in dt.Columns)
            {
                if (col.ColumnName == "CONTACT PERSON")
                {
                    IsExistcontactperson = true;
                }
            }



            StringBuilder sb = new StringBuilder();

            if (dt != null && IsExistEmail == true && IsExistcontactperson == true)
            {
                try
                {
                    // listView1.Items.Clear();
                    foreach (DataRow row in dt.Rows)
                    {
                        var ResultName = textBox2.Text + "\\" + string.Format(@"email{0}.docx", DateTime.Now.Ticks);

                        Document document = new Document();
                        document.LoadFromFile(textBox2.Text + "\\" + comboBox2.Text);
                        String contactPerson = row["contact person".ToUpper()].ToString();
                        document.Replace("<contact person>", contactPerson, false, true);

                        document.SaveToFile(ResultName, FileFormat.Docx);
                        // System.Diagnostics.Process.Start("Replace.docx");

                        //     dotx2docx("demo.dotx", ResultName);


                        //    Mailmerge(ResultName, row, dt.Columns);
                        //  String contactPerson = row["contact person".ToUpper()].ToString();
                        String Toemail = row["email".ToUpper()].ToString();

                        MailMessage          mail       = new MailMessage();
                        SmtpClient           SmtpServer = new SmtpClient(txtHost.Text);
                        System.Text.Encoding SystemEncoding;
                        SystemEncoding = System.Text.Encoding.UTF8;

                        mail.From = new MailAddress(txtForm.Text);
                        mail.To.Add(Toemail);
                        mail.Subject = txtSubjec.Text;

                        mail.IsBodyHtml = true;

                        System.Net.Mail.Attachment attachment;
                        attachment = new System.Net.Mail.Attachment(ResultName);
                        mail.Attachments.Add(attachment);

                        mail.Body = settings.Body; // GetTemplate("EmailDetial.txt").Replace("<contact person>", contactPerson);

                        SmtpServer.Port = Convert.ToInt32(settings.Port);
                        String Name     = txtName.Text;
                        String password = txtPassword.Text;

                        SmtpServer.Credentials = new System.Net.NetworkCredential(Name, password);
                        if (settings.Encryption == "SSL")
                        {
                            SmtpServer.EnableSsl = true;
                        }
                        else if (settings.Encryption == "")
                        {
                            SmtpServer.EnableSsl = false;
                        }
                        SmtpServer.Send(mail);
                        sb.Append(contactPerson + "--> " + Toemail + " is sent" + System.Environment.NewLine);
                        //MessageBox.Show("mail Send");
                    }
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    toolStripStatusLabel1.Text = (ex.ToString());
                }
            }
            else
            {
                if (IsExistcontactperson == false)
                {
                    toolStripStatusLabel1.Text = ("Missing contact person column in csv file");
                }
                if (IsExistEmail == false)
                {
                    toolStripStatusLabel1.Text = ("Missing contact email column in csv file");
                }
            }
            textBox1.Text = sb.ToString();
        }
        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));
        }