예제 #1
0
        public static string DOCToDOCX(string filepath)
        {
            string outputfilepath = string.Empty;

            /*
             * XWPFDocument doc = null;
             *
             * FileInfo fi = new FileInfo(filepath);
             * if (fi.Exists)
             * {
             *  using (FileStream fs = new FileStream(fi.FullName, FileMode.Open))
             *  {
             *      doc = new XWPFDocument(fs);
             *      outputfilepath = fi.FullName.Replace(fi.Extension, ".docx");
             *      FileStream out1 = new FileStream(outputfilepath, FileMode.Create);
             *      doc.Write(out1);
             *      out1.Close();
             *  }
             * }*/
            FileInfo fi = new FileInfo(filepath);

            if (fi.Exists)
            {
                Spire.Doc.Document doc = new Spire.Doc.Document();
                doc.LoadFromFile(fi.FullName);
                outputfilepath = fi.FullName.Replace(fi.Extension, ".docx");
                doc.SaveToFile(outputfilepath, Spire.Doc.FileFormat.Docx);
            }
            return(outputfilepath);
        }
예제 #2
0
파일: Utils.cs 프로젝트: iamHXQ/Oy
        /// <summary>
        /// 查找替换文本
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="strOld">查找文本</param>
        /// <param name="strNew">替换文本</param>
        public void WordReplace(string[] strOld, string[] strNew)
        {
            string[] SampleFilePaths = { @".\Resources\外封面.docx", @".\Resources\报告书.docx", @".\Resources\委托书.docx", @".\Resources\管理表.docx", @".\Resources\流程单.docx" };
            string   ProjectName     = NamedObjectDictionary.ReadFromNOD(lib.AppConfig.ProjectInfoName[1]);
            string   FolderPath      = Interaction.GetFolderPath();

            if (strOld.Length == strNew.Length)
            {
                using (Spire.Doc.Document doc = new Spire.Doc.Document())
                {
                    foreach (string SampleFilePath in SampleFilePaths)
                    {
                        string filename     = System.IO.Path.GetFileNameWithoutExtension(SampleFilePath) + "-" + ProjectName; //获取文件名
                        string extension    = System.IO.Path.GetExtension(SampleFilePath);                                    //获取扩展名
                        string saveFilePath = FolderPath + @"\" + filename + extension;                                       //合并成完整路径

                        doc.LoadFromFile(SampleFilePath);
                        for (int i = 0; i < strOld.Length; i++)
                        {
                            doc.Replace("[<" + strOld[i] + ">]", strNew[i], false, false);
                        }
                        if (saveFilePath != null)
                        {
                            doc.SaveToFile(saveFilePath);
                            doc.Close();
                        }
                    }
                }
            }
            else
            {
                Forms.MessageBox.Show("要替换的新旧字符串数量不同,取消操作");
            }
        }
        /// <summary>
        /// 将Pdf文档转换为xps文档
        /// </summary>
        /// <param name="wordDocName">word文档全路径</param>
        /// <param name="xpsDocName">xps文档全路径</param>
        /// <returns></returns>
        public static Boolean ConvertWordToXPS2(string wordDocName, string xpsDocName)
        {
            Boolean b = false;

            try
            {
                //初始化String类,元素为需要转换的Word文档

                //创建一个Document类对象,加载sample文件
                Spire.Doc.Document doc = new Spire.Doc.Document();
                doc.LoadFromFile(wordDocName);

                //  Spire.Doc.Section section =  new Spire.Doc.Section(null);
                // doc.Sections.Add(section);


                //设置文档的背景填充模式为颜色填充
                //  doc.Background.Type = BackgroundType.Color;
                //设置背景颜色
                //   doc.Background.Color = System.Drawing.Color.Transparent;

                //将Word文件保存为XPS,并运行生成的文档
                doc.SaveToFile(xpsDocName, Spire.Doc.FileFormat.XPS);
                b = true;
            }
            catch (Exception e1)
            {
                b = false;
                //  System.Windows.MessageBox.Show("word转换失败:" + e1.Message);
            }
            return(b);
        }
예제 #4
0
 public static bool SaveToPDF(string srcFileName, string dstFileName)
 {
     File.Delete(dstFileName);
     using (Spire.Doc.Document doc = new Spire.Doc.Document(srcFileName))
     {
         doc.SaveToFile(dstFileName, Spire.Doc.FileFormat.PDF);
     }
     return(File.Exists(dstFileName));
 }
예제 #5
0
        public void CorruptedMathTypeEquation_SaveDocumentAsDoc_CallToWordOpenXMLWillNoLongerWork()
        {
            var inputPath = "test-inputs/CH7594-Corrupted MathType Equation.doc";

            this.Invoking(y => y.GetOpenXml(inputPath)).Should().NotThrow("before save call to WordOpenXML still works");

            var outputFilePath = $"{OutputPath}/{nameof(CorruptedMathTypeEquation_SaveDocumentAsDoc_CallToWordOpenXMLWillNoLongerWork)}.doc";

            using var doc = new Document(inputPath);
            doc.SaveToFile(outputFilePath);

            this.Invoking(y => y.GetOpenXml(outputFilePath)).Should().NotThrow("call to WordOpenXML still works as document is saved as .doc");
        }
 /// <summary>
 /// 替换Word
 /// </summary>
 /// <param name="path"></param>
 /// <param name="dics"></param>
 /// <param name="savePath"></param>
 /// <returns></returns>
 public bool WordReplace(string path, string savePath, Dictionary <string, string> dics)
 {
     using (var doc = new Spire.Doc.Document())
     {
         doc.LoadFromFile(path);
         foreach (var item in dics)
         {
             doc.Replace(new Regex(item.Key), item.Value);
         }
         doc.SaveToFile(savePath);
         doc.Close();
     }
     return(true);
 }
예제 #7
0
 /// <summary>
 /// Word转换PDF
 /// </summary>
 /// <param name="fileName">文件名称</param>
 public static void WordToPDF(string fileName)
 {
     try
     {
         if (!FileHelper.IsExistFile(fileName.Substring(0, fileName.LastIndexOf(".")) + ".pdf"))
         {
             Stream stream   = File.OpenRead(fileName);
             var    document = new Spire.Doc.Document();
             document.LoadFromFile(fileName);
             document.SaveToFile(fileName.Substring(0, fileName.LastIndexOf(".")) + ".pdf", Spire.Doc.FileFormat.PDF);
         }
     }
     catch (Exception ex)
     {
         throw ExceptionEx.Throw(ex);
     }
 }
예제 #8
0
 public static bool SaveFile1(string filePath, MyNode myNode)
 {
     try
     {
         Spire.Doc.Document doc = new Spire.Doc.Document();
         doc.LoadFromFile(filePath);
         while (doc.Sections[0].Paragraphs.Count != 0)
         {
             doc.Sections[0].Paragraphs.RemoveAt(0);
         }
         saveNode(doc, myNode, 1);
         doc.SaveToFile(filePath);
         return(true);
     }
     catch (Exception e)
     {
         return(false);
     }
 }
예제 #9
0
        static void Main(string[] args)
        {
            // var word_file = args[0];
            // var pdf_file = args[1];

            var word_file = "./result/result.docx";
            var pdf_file  = "./result/result.pdf";

            Console.WriteLine(word_file);
            Console.WriteLine(pdf_file);

            var watch = System.Diagnostics.Stopwatch.StartNew();

            Spire.Doc.Document pdfdoc = new Spire.Doc.Document(word_file, Spire.Doc.FileFormat.Auto);
            pdfdoc.SaveToFile(pdf_file, Spire.Doc.FileFormat.PDF);

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            Console.WriteLine($"Completed in {elapsedMs / 1000} seconds {elapsedMs % 1000} milliseconds");
        }
예제 #10
0
        public static bool InsertTextInPlaceholders_spire(string templatePath, string outputDocumentPath, Object obj)
        {
            try
            {
                if (!File.Exists(templatePath))
                {
                    throw new FileNotFoundException();
                }

                //Creates Document instance
                Spire.Doc.Document document = new Spire.Doc.Document();

                //Loads the word document
                document.LoadFromFile(templatePath);

                // Gets the collection of all the merge field names
                string[] MergeFieldNames    = document.MailMerge.GetMergeFieldNames();
                var      myMergeFieldValues = new List <string>();
                foreach (var reqField in MergeFieldNames)
                {
                    myMergeFieldValues.Add(obj.GetPropertyStringValue(reqField));
                }

                //var myMergeFieldNames = obj.GetPublicStringPropertiesNames();
                document.MailMerge.Execute(MergeFieldNames, myMergeFieldValues.ToArray());

                document.SaveToFile(outputDocumentPath);

                return(true);
            }
            catch (Exception x)
            {
                XLogger.Error(x);
                return(false);
            }
        }
예제 #11
0
        /// <summary>
        /// 文件上传
        /// </summary>
        public void UploadFiles()
        {
            bool result = false;

            if (Request.Form["option"].ToString() == "update")
            {
                string fn      = Request.Form["filename"].ToString();
                string keyword = Request.Form["keyword"].ToString();
                string status  = Request.Form["ispublic"].ToString() == "checked" ? "1" : "0";
                string id      = Request.Form["id"].ToString();
                string sql     = string.Format("update fileinfo set filename='{0}',keyword='{1}',status='{2}' where keyid={3}", fn, keyword, status, id);
                int    i       = DAL.Commons.Instance.chooseFactory("sql").ExecuteNonQuery(sql);
                result = i > 0 ? true : false;
            }
            else
            {
                if (Request.Files.Count > 0)
                {
                    loginUser lu  = Session["user"] as loginUser;
                    string    dir = string.Format("{0}//{1}//{2}", "upload", DateTime.Now.ToString("yyyy-MM-dd"), lu.LoginName);

                    string extName = Path.GetExtension(Request.Files[0].FileName);//.Split('.')[1].ToLower();
                    extName = extName.Substring(1);
                    string filename = DAL.Commons.Instance.GetUploadFileName(dir, extName);
                    Request.Files[0].SaveAs(AppDomain.CurrentDomain.BaseDirectory + filename);
                    string fn       = Request.Form["filename"].ToString();
                    string keyword  = Request.Form["keyword"].ToString();
                    string dirid    = Request.Form["dirid"].ToString();
                    string userid   = lu.ID;
                    string status   = Request.Form["ispublic"].ToString() == "checked" ? "1" : "0";
                    string f1       = "doc,docx";
                    string f2       = "xls,xlsx";
                    string f3       = "txt,jpeg,png";
                    string f4       = "pdf";
                    int    viewmode = 3;
                    string viewdir  = "";
                    if (f1.IndexOf(extName) >= 0)
                    {
                        viewmode = 1;
                        Spire.Doc.Document doc = new Spire.Doc.Document();
                        doc.LoadFromFile(AppDomain.CurrentDomain.BaseDirectory + filename);
                        string newname = DAL.Commons.Instance.GetUploadFileName(dir, "pdf");
                        doc.SaveToFile(AppDomain.CurrentDomain.BaseDirectory + newname, Spire.Doc.FileFormat.PDF);
                        viewdir = newname;
                        doc.Close();
                    }
                    else if (f2.IndexOf(extName) >= 0)
                    {
                        viewmode = 1;
                        Spire.Xls.Workbook book = new Spire.Xls.Workbook();
                        book.LoadFromFile(AppDomain.CurrentDomain.BaseDirectory + filename);
                        string newname = DAL.Commons.Instance.GetUploadFileName(dir, "pdf");
                        book.ConverterSetting.SheetFitToPage = true;
                        book.SaveToFile(AppDomain.CurrentDomain.BaseDirectory + newname, Spire.Xls.FileFormat.PDF);
                        viewdir = newname;
                    }
                    else if (f3.IndexOf(extName) >= 0)
                    {
                        viewmode = 2;
                        viewdir  = filename;
                    }
                    else if (f4.IndexOf(extName) >= 0)
                    {
                        viewmode = 1;
                        viewdir  = filename;
                    }
                    Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();


                    string sql = string.Format("insert into fileinfo (filename,keyword,dirid,userid,status,localdir,viewdir,viewmode,extname) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", fn, keyword, dirid, userid, status, filename, viewdir, viewmode, extName);
                    int    i   = DAL.Commons.Instance.chooseFactory("sql").ExecuteNonQuery(sql);
                    result = i > 0 ? true : false;
                }
            }
            var par = new { sucess = result };

            Response.Write(DAL.Commons.Instance.ToJson(par));
        }
예제 #12
0
        private void button1_Click(object sender, EventArgs e)
        {
            string filename = Application.StartupPath + "\\bin\\" + Global.templateName + ".doc";

            Spire.Doc.Document document = new Spire.Doc.Document(filename, Spire.Doc.FileFormat.Docx);

            Spire.Doc.Fields.TextBox      textBox   = document.TextBoxes[9];
            Spire.Doc.Documents.Paragraph paragraph = textBox.Body.AddParagraph();
            Spire.Doc.Fields.TextRange    textRange = paragraph.AppendText(textBox1.Text);
            document.SaveToFile(filename, Spire.Doc.FileFormat.Docx);

            object filename1     = Environment.CurrentDirectory.ToString() + "\\bin\\" + Global.templateName + ".doc";
            string ImagePath     = pictureBox1.ImageLocation;
            string strKey        = "7.3.3监控系统测点温度与验证测点及均匀性温度分布对比图";
            object MissingValue  = Type.Missing;
            bool   isFindSealLoc = false;

            Microsoft.Office.Interop.Word.Application wp = null;
            Microsoft.Office.Interop.Word.Document    wd = null;
            try
            {
                wp = new Microsoft.Office.Interop.Word.Application();
                wd = wp.Documents.Open(ref filename1, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue,
                                       ref MissingValue, ref MissingValue);
                wp.Selection.Find.ClearFormatting();
                wp.Selection.Find.Replacement.ClearFormatting();
                wp.Selection.Find.Text = strKey;
                object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
                if (wp.Selection.Find.Execute(ref MissingValue, ref MissingValue, ref MissingValue,
                                              ref MissingValue, ref MissingValue, ref MissingValue,
                                              ref MissingValue, ref MissingValue, ref MissingValue,
                                              ref MissingValue, ref objReplace, ref MissingValue,
                                              ref MissingValue, ref MissingValue, ref MissingValue))
                {
                    object Anchor           = wp.Selection.Range;
                    object LinkToFile       = false;
                    object SaveWithDocument = true;
                    Microsoft.Office.Interop.Word.InlineShape Inlineshape = wp.Selection.InlineShapes.AddPicture(
                        ImagePath, ref LinkToFile, ref SaveWithDocument, ref Anchor);
                    Inlineshape.Select();
                    Microsoft.Office.Interop.Word.Shape shape = Inlineshape.ConvertToShape();
                    shape.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapBehind;

                    isFindSealLoc = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (wd != null)
                {
                    wd.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wd);
                    wd = null;
                }
                if (wp != null)
                {
                    wp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wp);
                    wp = null;
                }
                MessageBox.Show("导入成功!");
            }

            this.Close();
        }
예제 #13
0
        public ActionResult CreateDocumentsFromTemplate(ContractDetails details)
        {
            //Get data from db for current user
            DSGVOEntities1 db = new DSGVOEntities1();


            kunden CurrentUser = db.kundens.Where(t => t.plz == details.UserZip.ToString().Trim() && t.seriennr.Substring(15).Trim() == details.SerialNo.ToString().Trim()).First();

            ////Update contractuser in db
            //CurrentUser.contractuser = details.ContractUser.ToString().Trim();

            ////Change email if it is changed
            //if (CurrentUser.email.ToString().Trim() != details.Email.ToString().Trim())
            //{
            //    CurrentUser.email = details.Email.ToString().Trim();
            //}

            //db.SaveChanges();


            //Check if changes in data exist and send it in email
            StringBuilder dataChanges = new StringBuilder();

            bool ChangesExist = false;

            dataChanges.Append("<table>");
            dataChanges.Append(" <tr><th>Previous data</th><th>Changed data from user</th></tr>");


            if (CurrentUser.name1.ToString().Trim() != details.Name1.ToString().Trim())
            {
                ChangesExist = true;
                dataChanges.Append(" <tr><td>" + CurrentUser.name1.ToString().Trim() + " </td><td>" + details.Name1.ToString().Trim() + "</td></tr>");
                CurrentUser.name1 = details.Name1.ToString().Trim();
            }

            if (CurrentUser.name2.ToString().Trim() != details.Name2.ToString().Trim())
            {
                ChangesExist = true;
                dataChanges.Append(" <tr><td>" + CurrentUser.name2.ToString().Trim() + " </td><td>" + details.Name2.ToString().Trim() + "</td></tr>");
                CurrentUser.name2 = details.Name2.ToString().Trim();
            }

            if (CurrentUser.strasse.ToString().Trim() != details.Street.ToString().Trim())
            {
                ChangesExist = true;
                dataChanges.Append(" <tr><td>" + CurrentUser.strasse.ToString().Trim() + " </td><td>" + details.Street.ToString().Trim() + "</td></tr>");
                CurrentUser.strasse = details.Street.ToString().Trim();
            }

            if (CurrentUser.plz.ToString().Trim() != details.Zip.ToString().Trim())
            {
                ChangesExist = true;
                dataChanges.Append(" <tr><td>" + CurrentUser.plz.ToString().Trim() + " </td><td>" + details.Zip.ToString().Trim() + "</td></tr>");
                CurrentUser.plz = details.Zip.ToString().Trim();
            }

            if (CurrentUser.ort.ToString().Trim() != details.City.ToString().Trim())
            {
                ChangesExist = true;
                dataChanges.Append(" <tr><td>" + CurrentUser.ort.ToString().Trim() + " </td><td>" + details.City.ToString().Trim() + "</td></tr>");
                CurrentUser.ort = details.City.ToString().Trim();
            }

            //if (CurrentUser.land.ToString().Trim() != details.Country.ToString().Trim())
            //{
            //    ChangesExist = true;
            //    dataChanges.Append(" <tr><td>" + CurrentUser.land.ToString().Trim() + " </td><td>" + details.Country.ToString().Trim() + "</td></tr>");

            //}

            if (CurrentUser.email.ToString().Trim() != details.Email.ToString().Trim())
            {
                ChangesExist = true;
                dataChanges.Append(" <tr><td>" + CurrentUser.email.ToString().Trim() + " </td><td>" + details.Email.ToString().Trim() + "</td></tr>");
                CurrentUser.email = details.Email.ToString().Trim();
            }

            //if (CurrentUser.contractuser == null)
            //{
            //    ChangesExist = true;
            //    dataChanges.Append(" <tr><td>Empty</td><td>" + details.ContractUser.ToString().Trim() + "</td></tr>");

            //}



            ////Adding user data to viewbag
            //if (CurrentUser.name1 != null)
            //{
            //    details.Name1 = CurrentUser.name1.ToString().Trim();
            //}

            //if (CurrentUser.name2 != null)
            //{
            //    details.Name2 = CurrentUser.name2.ToString().Trim();
            //}

            //if (CurrentUser.strasse != null)
            //{
            //    details.Street= CurrentUser.strasse.ToString().Trim() + " " ;
            //}



            //if (CurrentUser.ort != null)
            //{
            //    details.City= CurrentUser.ort.ToString().Trim();
            //}

            //if (CurrentUser.land != null)
            //{
            //    //Set country
            //    switch (CurrentUser.land.ToString().Trim())
            //    {
            //        case "D":
            //            CurrentUser.land = "Deutschland";
            //            break;
            //        case "A":
            //            CurrentUser.land = "Österreich";
            //            break;
            //        case "CH":
            //            CurrentUser.land = "Schweiz";
            //            break;
            //        default:
            //            break;
            //    }


            //    details.Country = CurrentUser.land.ToString().Trim();
            //}

            //if (CurrentUser.email != null)
            //{
            //    details.Contact = CurrentUser.email.ToString().Trim();
            //}


            // Set country
            switch (details.Country.ToString().Trim())
            {
            case "D":
                details.Country = "Deutschland";
                break;

            case "A":
                details.Country = "Österreich";
                break;

            case "CH":
                details.Country = "Schweiz";
                break;

            default:
                break;
            }


            string Result, Name;

            //Generating strong name as word and pdf name
            string HashName = UserInfo.CalculateMD5Hash(details.SerialNo + "-" + details.UserZip);


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

                document.LoadFromFile(Server.MapPath("~/Template/template.docx").ToString());


                if (details.Name1 != null && details.Name1.ToString().Trim() != "")
                {
                    document.Replace("##AGName1##", details.Name1, false, true);
                }

                else
                {
                    document.Replace("##AGName1##", "", false, true);
                }

                if (details.Name2 != null && details.Name2.ToString().Trim() != "")
                {
                    document.Replace("##AGName2##", details.Name2, false, true);
                }

                else
                {
                    document.Replace("##AGName2##", "", false, true);
                }

                if (details.Street != null && details.Street.ToString().Trim() != "")
                {
                    document.Replace("##AGStreet##", details.Street, false, true);
                }

                else
                {
                    document.Replace("##AGStreet##", "", false, true);
                }


                if (details.Zip != null && details.Zip.ToString().Trim() != "")
                {
                    document.Replace("##AGZIP##", details.Zip, false, true);
                }

                else
                {
                    document.Replace("##AGZIP##", "", false, true);
                }


                if (details.City != null && details.City.ToString().Trim() != "")
                {
                    document.Replace("##AGCITY##", details.City, false, true);
                    document.Replace("##City##", details.City, false, true);
                }

                else
                {
                    document.Replace("##AGCITY##", "", false, true);
                    document.Replace("##City##", "", false, true);
                }

                if (details.Country != null && details.Country.ToString().Trim() != "")
                {
                    document.Replace("##AGCountry##", details.Country, false, true);
                }

                else
                {
                    document.Replace("##AGCountry##", "", false, true);
                }

                if (details.ContractUser != null && details.ContractUser.ToString().Trim() != "")
                {
                    document.Replace("##ContractUser##", details.ContractUser, false, true);
                }


                if (details.Email != null && details.Email.ToString().Trim() != "")
                {
                    document.Replace("##AGCONTACT##", details.Email, false, true);
                }

                else
                {
                    document.Replace("##AGCONTACT##", "", false, true);
                }


                document.Replace("##DayDate##", DateTime.Now.ToString("dd.MM.yyyy"), false, true);

                document.SaveToFile(Server.MapPath("~/Word/").ToString() + HashName + ".docx", Spire.Doc.FileFormat.Docx);


                //Code for making connection with existing word template
                Microsoft.Office.Interop.Word._Application wApp  = new Microsoft.Office.Interop.Word.Application();
                Microsoft.Office.Interop.Word.Documents    wDocs = wApp.Documents;
                Microsoft.Office.Interop.Word._Document    wDoc  = wDocs.Open(Server.MapPath("~/Word/").ToString() + HashName + ".docx", ReadOnly: false, Visible: false);
                wDoc.Activate();

                string pdfName = @Server.MapPath("~/Pdf/").ToString() + HashName + ".pdf";

                //wDoc.ExportAsFixedFormat(OutputFileName: pdfName, ExportFormat: WdExportFormat.wdExportFormatPDF, UseISO19005_1: true);
                wDoc.ExportAsFixedFormat(
                    pdfName,
                    WdExportFormat.wdExportFormatPDF,
                    OptimizeFor: WdExportOptimizeFor.wdExportOptimizeForPrint,
                    BitmapMissingFonts: true,
                    DocStructureTags: false,
                    UseISO19005_1: true);

                wDoc.Close();


                //Update fields into db
                CurrentUser.contractuser   = details.ContractUser;
                CurrentUser.contactperson  = details.ContractUser;
                CurrentUser.contractsigned = true;
                CurrentUser.signeddate     = DateTime.Now;
                CurrentUser.contractname   = HashName + ".pdf";



                //Send email with pdf as attachment to office
                SmtpClient        smtpClient      = new SmtpClient();
                NetworkCredential basicCredential =
                    new NetworkCredential("*****@*****.**", "hopeDSGVO");
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                MailAddress fromAddress             = new MailAddress("*****@*****.**");

                smtpClient.Host = "smtp.1und1.de";
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials           = basicCredential;

                smtpClient.Port      = 587;
                smtpClient.EnableSsl = true;

                message.From    = fromAddress;
                message.Subject = "hope-DSGVO - AV-Vertrag, Kunde: " + details.UserZip + " - hotel: " + details.Name1;

                message.Attachments.Add(new System.Net.Mail.Attachment(Server.MapPath("~/Pdf/").ToString() + HashName + ".pdf"));

                //[email protected]

                message.To.Add(new MailAddress("*****@*****.**"));


                smtpClient.Send(message);


                //Send email to customer
                SmtpClient        smtpCustomer            = new SmtpClient();
                NetworkCredential basicCredentialCustomer =
                    new NetworkCredential("*****@*****.**", "hopeDSGVO");
                System.Net.Mail.MailMessage messageCustomer = new System.Net.Mail.MailMessage();
                MailAddress fromAddressCompany = new MailAddress("*****@*****.**");

                smtpCustomer.Host = "smtp.1und1.de";
                smtpCustomer.UseDefaultCredentials = false;
                smtpCustomer.Credentials           = basicCredential;

                smtpCustomer.Port      = 587;
                smtpCustomer.EnableSsl = true;

                messageCustomer.From    = fromAddressCompany;
                messageCustomer.Subject = "hope-DSGVO - AV-Vertrag, Kunde: " + details.UserZip + " - hotel: " + details.Name1;

                messageCustomer.Attachments.Add(new System.Net.Mail.Attachment(Server.MapPath("~/Pdf/").ToString() + HashName + ".pdf"));

                //[email protected]

                messageCustomer.To.Add(new MailAddress(CurrentUser.email.ToString().Trim()));

                smtpCustomer.Send(messageCustomer);



                //Send email if user changed data on html form [email protected]

                if (ChangesExist)
                {
                    //Send email with pdf as attachemnt
                    SmtpClient        smtpClientSecond      = new SmtpClient();
                    NetworkCredential basicCredentialSecond =
                        new NetworkCredential("*****@*****.**", "hopeDSGVO");
                    System.Net.Mail.MailMessage messageSecond = new System.Net.Mail.MailMessage();
                    MailAddress fromAddressSecond             = new MailAddress("*****@*****.**");

                    smtpClientSecond.Host = "smtp.1und1.de";
                    smtpClientSecond.UseDefaultCredentials = false;
                    smtpClientSecond.Credentials           = basicCredential;

                    smtpClientSecond.Port      = 587;
                    smtpClientSecond.EnableSsl = true;

                    messageSecond.From    = fromAddress;
                    messageSecond.Subject = "hope-DSGVO - Kundendaten geändert: " + details.UserZip + " - hotel: " + details.Name1;


                    messageSecond.IsBodyHtml = true;

                    messageSecond.Body = dataChanges.ToString();
                    //[email protected]

                    messageSecond.To.Add(new MailAddress("*****@*****.**"));


                    smtpClientSecond.Send(message);

                    //Update field in database
                    CurrentUser.datachanged = true;
                }



                //Update field in database
                db.SaveChanges();



                return(Json(new { Result = "true", Name = HashName }));
            }

            catch (Exception ex)
            {
                Console.WriteLine("Error occured:", ex.ToString());
                return(Json(Result = ex.ToString()));
            }

            finally
            {
                Dispose();
            }
        }
예제 #14
0
        protected Dictionary <string, string> convierteArchivoA(string ruta, string nombreArchivo, string formato, string cliente)
        {
            Dictionary <string, string> res = new Dictionary <string, string>();

            res.Add("estatus", "error");
            Document    document         = null;
            Application applicationclass = null;

            applicationclass = new Application();

            object missingType       = Type.Missing;
            object readOnly          = true;
            object isVisible         = false;
            object rutaArchivo       = ruta + nombreArchivo;
            object formatoConversion = tipoArchivo(formato);
            object rutaArchivoConver = ruta + Path.GetFileNameWithoutExtension(ruta + nombreArchivo) + "." + formato;
            string archivoNomFinal   = Path.GetFileNameWithoutExtension(ruta + nombreArchivo) + "." + formato;

            if (formato.Equals("xml"))
            {
                ProcesaDocumento pd = new ProcesaDocumento(ruta + nombreArchivo, ruta, parametrosXML);
                if (pd.procesa())
                {
                    if (!pd.generaXMLV4())
                    {
                        res.Add("mensaje", pd.Mensaje);
                    }
                }
                else
                {
                    res.Add("mensaje", pd.Mensaje);
                }
            }
            else if (formato.Equals("epub"))
            {
                Spire.Doc.Document documento = new Spire.Doc.Document();
                documento.LoadFromFile(rutaArchivo.ToString());
                documento.SaveToFile(rutaArchivoConver.ToString(), Spire.Doc.FileFormat.EPub);
            }
            else
            {
                applicationclass.Documents.Open(ref rutaArchivo,
                                                ref readOnly,
                                                ref missingType, ref missingType, ref missingType,
                                                ref missingType, ref missingType, ref missingType,
                                                ref missingType, ref missingType, ref isVisible,
                                                ref missingType, ref missingType, ref missingType,
                                                ref missingType, ref missingType);

                applicationclass.Visible = false;
                document = applicationclass.ActiveDocument;


                document.SaveAs(ref rutaArchivoConver, ref formatoConversion, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType);

                document.Close(ref missingType, ref missingType, ref missingType);
                applicationclass.Quit();
            }

            if (formato.Equals("html"))
            {
                aplicaFormato(rutaArchivoConver.ToString(), Path.GetFileNameWithoutExtension(ruta + nombreArchivo));
            }

            if (File.Exists(rutaArchivoConver.ToString()))
            {
                bool comprimido = comprime(ruta, archivoNomFinal, formato);
                if (comprimido)
                {
                    string nombreArchivoZip = Path.GetFileNameWithoutExtension(nombreArchivo) + ".zip";
                    string urlServidor      = urlServer + "descargar.ashx?cliente=" + cliente + "&archivo=" + nombreArchivoZip;
                    res.Add("downloadURL", urlServidor);
                    res["estatus"] = "exito";
                    res.Add("zipFileName", nombreArchivoZip);
                    res.Add("fileName", Path.GetFileNameWithoutExtension(ruta + nombreArchivo) + "." + formato);
                    res.Add("imageFolder", "images");
                    res.Add("convertionType", formato);
                    ;
                }
                else
                {
                    res.Add("mensaje", "No se puede comprimir el archivo");
                }
            }

            return(res);
        }
예제 #15
0
        /// <summary>
        /// 对Word文档进行拆分
        /// </summary>
        /// <param name="wordPath">要拆分的Word文档路径</param>
        /// <param name="savePath">拆分后的Word存储路径</param>
        private void SplitWord(string wordPath, string savePath)
        {
            object missing = System.Reflection.Missing.Value; //作为方法传参中的缺省值

            if (!Directory.Exists(savePath))                  //判断Word存储路径是否存在
            {
                Directory.CreateDirectory(savePath);          //如果路径不存在,则创建
            }
            try
            {
                //判断拆分方式:0表示按书签拆分,1表示按分页符拆分,默认为按书签拆分
                switch (flag)
                {
                    #region  书签拆分
                case 0:
                default:
                    Document doc = null;                    //声明一个Word文档对象
                    if (doc == null)                        //判断Word文档对象是否为空
                    {
                        doc = ReadDocument(wordPath);       //调用方法读取指定Word内容,并实例化Word文档对象
                    }
                    int[,] positions = GetPosition(doc);    //获取指定Word中的所有书签的开始和结束位置
                    object oStart = 0;                      //定义变量,表示要拆分的开始位置
                    object oEnd   = 0;                      //定义变量,表示要拆分的结束位置
                    int    row    = positions.GetLength(0); //获取二维数组的行数
                    for (int i = 0; i < row; i++)           //遍历二维数组的所有行
                    {
                        if (i != row - 1)                   //判断是否为最后一行
                        {
                            oEnd = positions[i, 1];         //如果不是最后一行,记录值,作为拆分的结束位置
                        }
                        else
                        {
                            oEnd = doc.Content.End;                     //如果是最后一行,则直接将Word文档的最后位置作为拆分的结束位置
                        }
                        Range tocopy = doc.Range(ref oStart, ref oEnd); //使用开始和结束位置锁定要拆分的范围
                        tocopy.Copy();                                  //复制要拆分范围内容的所有内容
                        Document docto = CreateDocument(textBox1.Text); //调用自定义方法创建一个新的Word文档
                        docto.Content.Paste();                          //将复制的内容粘贴到新创建的Word文档中
                        //设置Word文档的保存路径及文件名(以编号命名)
                        object filename = savePath + "\\" + i.ToString("000") + ".docx";
                        //保存Word文档
                        docto.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing,
                                     ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                                     ref missing, ref missing, ref missing, ref missing, ref missing);
                        docto.Close(ref missing, ref missing, ref missing); //关闭Word文档
                        oStart = oEnd;                                      //将本次拆分的结束位置作为下一次拆分的开始位置
                    }
                    break;
                    #endregion

                    #region  分页符拆分
                case 1:
                    Spire.Doc.Document original = new Spire.Doc.Document();             //使用Spire插件创建Word文档对象
                    original.LoadFromFile(wordPath);                                    //加载要拆分的Word文档
                    Spire.Doc.Document newWord = new Spire.Doc.Document(textBox1.Text); //使用选择的模板创建一个新的Word文档对象
                    Spire.Doc.Section  section = newWord.AddSection();                  //为新创建的Word文档添加一节
                    int index = 0;                                                      //根据分页来拆分文档
                    foreach (Spire.Doc.Section sec in original.Sections)                //遍历文档所有节
                    {
                        //遍历文档所有子对象
                        foreach (Spire.Doc.DocumentObject obj in sec.Body.ChildObjects)
                        {
                            if (obj is Spire.Doc.Documents.Paragraph)    //判断是否为段落
                            {
                                //创建Word文档中的段落对象
                                Spire.Doc.Documents.Paragraph para = obj as Spire.Doc.Documents.Paragraph;
                                //复制并添加原有段落对象到新文档
                                section.Body.ChildObjects.Add(para.Clone());
                                //遍历所有段落子对象
                                foreach (Spire.Doc.DocumentObject parobj in para.ChildObjects)
                                {
                                    //判断是否为分页符
                                    if (parobj is Spire.Doc.Break && (parobj as Spire.Doc.Break).BreakType == Spire.Doc.Documents.BreakType.PageBreak)
                                    {
                                        //获取段落分页并移除,保存新文档到文件夹
                                        int i = para.ChildObjects.IndexOf(parobj);
                                        section.Body.LastParagraph.ChildObjects.RemoveAt(i);
                                        newWord.SaveToFile(savePath + "\\" + index.ToString("000") + ".docx", Spire.Doc.FileFormat.Docx);
                                        index++;
                                        //实例化Document类对象,添加section,将原文档段落的子对象复制到新文档
                                        newWord = new Spire.Doc.Document(textBox1.Text);
                                        section = newWord.AddSection();
                                        section.Body.ChildObjects.Add(para.Clone());
                                        if (section.Paragraphs[0].ChildObjects.Count == 0)
                                        {
                                            section.Body.ChildObjects.RemoveAt(0);    //移除第一个空白段落
                                        }
                                        else
                                        {
                                            //删除分页符前的子对象
                                            while (i >= 0)
                                            {
                                                section.Paragraphs[0].ChildObjects.RemoveAt(i);
                                                i--;
                                            }
                                        }
                                    }
                                }
                            }
                            //若对象为表格,则添加表格对象到新文档
                            if (obj is Spire.Doc.Table)
                            {
                                section.Body.ChildObjects.Add(obj.Clone());
                            }
                        }
                    }
                    //拆分后的新文档保存至指定文档
                    newWord.SaveToFile(savePath + "\\" + index.ToString("00") + ".docx", Spire.Doc.FileFormat.Docx);
                    original.Close();
                    original.Dispose();
                    newWord.Close();
                    newWord.Dispose();
                    foreach (string file in Directory.GetFiles(savePath)) //遍历拆分完的所有Word文档
                    {
                        deletePagesInFile(file, 1, 1);                    //删除第一页
                    }
                    break;
                    #endregion
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }//异常跳过
        }