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
        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"));
        }
Beispiel #3
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();
        }
Beispiel #4
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);
            }
        }