Exemplo n.º 1
0
        public ActionResult Document(HttpPostedFileBase file)
        {
            if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path     = Path.Combine(Server.MapPath("~/App_Data"), fileName);
                file.SaveAs(path);


                object            Sourcepath = path;
                object            TargetPath = Server.MapPath("~/App_Data/document.html");
                Word._Application newApp     = new Word.Application();
                Word.Documents    d          = newApp.Documents;
                object            Unknown    = Type.Missing;
                Word.Document     od         = d.Open(ref Sourcepath, ref Unknown,
                                                      ref Unknown, ref Unknown, ref Unknown,
                                                      ref Unknown, ref Unknown, ref Unknown,
                                                      ref Unknown, ref Unknown, ref Unknown,
                                                      ref Unknown, ref Unknown, ref Unknown, ref Unknown);
                object format = Word.WdSaveFormat.wdFormatHTML;



                newApp.ActiveDocument.SaveAs(ref TargetPath, ref format,
                                             ref Unknown, ref Unknown, ref Unknown,
                                             ref Unknown, ref Unknown, ref Unknown,
                                             ref Unknown, ref Unknown, ref Unknown,
                                             ref Unknown, ref Unknown, ref Unknown,
                                             ref Unknown, ref Unknown);

                newApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
            }
            return(View());
        }
Exemplo n.º 2
0
        public override void Convert(String inputFile, String outputFile)
        {
            Object nothing = System.Reflection.Missing.Value;

            try
            {
                if (!File.Exists(inputFile))
                {
                    throw new ConvertException("File not Exists");
                }

                if (IsPasswordProtected(inputFile))
                {
                    throw new ConvertException("Password Exist");
                }

                app  = new Word.Application();
                docs = app.Documents;
                doc  = docs.Open(inputFile, false, true, false, nothing, nothing, true, nothing, nothing, nothing, nothing, false, false, nothing, true, nothing);
                doc.ExportAsFixedFormat(outputFile, Word.WdExportFormat.wdExportFormatPDF, false, Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 1, 1, Word.WdExportItem.wdExportDocumentContent, false, false, Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, false, false, false, nothing);
            }
            catch (Exception e)
            {
                release();
                throw new ConvertException(e.Message);
            }
            release();
        }
Exemplo n.º 3
0
        public override void Convert(String inputFile, String outputFile)
        {
            Object nothing = System.Reflection.Missing.Value;
            try
            {
                if (!File.Exists(inputFile))
                {
                    throw new ConvertException("File not Exists");
                }

                if (IsPasswordProtected(inputFile))
                {
                    throw new ConvertException("Password Exist");
                }

                app = new Word.Application();
                docs = app.Documents;
                doc = docs.Open(inputFile, false, true, false, nothing, nothing, true, nothing, nothing, nothing, nothing, false, false, nothing, true, nothing);
                doc.ExportAsFixedFormat(outputFile, Word.WdExportFormat.wdExportFormatPDF, false, Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 1, 1, Word.WdExportItem.wdExportDocumentContent, false, false, Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, false, false, false, nothing);
            }
            catch (Exception e)
            {
                release();
                throw new ConvertException(e.Message);
            }
            release();
        }
Exemplo n.º 4
0
 public MSWord_Controller(string filepath)
 {
     wordApp         = new Word.Application();
     wordApp.Visible = true;
     docs            = wordApp.Documents;
     doc             = docs.Open(filepath);
 }
Exemplo n.º 5
0
        public void GenerateWordFile()
        {
            Word._Application wApp  = new Word.Application();
            Word.Documents    wDocs = wApp.Documents;
            Word._Document    wDoc  = wDocs.Open(@"C:\Users\s.stadtler\source\repos\FST01\Sourcecode\FST.TournamentPlanner\FST.TournamentPlanner.Test\Urkunde_v1_edit.docx", ReadOnly: false);
            wDoc.Activate();

            Word.Bookmarks wBookmarks = wDoc.Bookmarks;
            Word.Bookmark  wBookmark  = wBookmarks["Tuniername"];
            Word.Range     wRange     = wBookmark.Range;
            wRange.Text = "Supertunier";
        }
Exemplo n.º 6
0
        public ActionResult ReadTable(HttpPostedFileBase uploadfile)
        {
            uploadfile.SaveAs(Server.MapPath("\\Resume\\") + uploadfile.FileName);
            string filepath = Server.MapPath("\\Resume\\" + uploadfile.FileName.ToString());

            Microsoft.Office.Interop.Word.Application app  = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Documents   docs = app.Documents;
            Document doc   = docs.Open(filepath, ReadOnly: true);
            Table    t     = doc.Tables[1];
            Range    r     = t.Range;
            Cells    cells = r.Cells;

            tbl_model tmodel = new tbl_model();

            tmodel.name          = cells[3].Range.Text.ToString();
            tmodel.cnt           = cells[5].Range.Text.ToString();
            tmodel.qualification = cells[7].Range.Text;
            tmodel.email         = cells[9].Range.Text;

            for (int i = 1; i <= cells.Count; i++)
            {
                Cell   cell = cells[i];
                Range  r2   = cell.Range;
                String txt  = r2.Text;
                Marshal.ReleaseComObject(cell);
                Marshal.ReleaseComObject(r2);
            }

            //Rows rows = t.Rows;
            //Columns cols = t.Columns;
            // Cannot access individual rows in this collection because the table has vertically merged cells.
            //for (int i = 0; i < rows.Count; i++) {
            //  for (int j = 0; j < cols.Count; j++) {
            //      Cell cell = rows[i].Cells[j];
            //      Range r = cell.Range;
            //  }
            //}

            doc.Close(false);
            app.Quit(false);
            //Marshal.ReleaseComObject(cols);
            //Marshal.ReleaseComObject(rows);
            Marshal.ReleaseComObject(cells);
            Marshal.ReleaseComObject(r);
            Marshal.ReleaseComObject(t);
            Marshal.ReleaseComObject(doc);
            Marshal.ReleaseComObject(docs);
            Marshal.ReleaseComObject(app);
            return(View(tmodel));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Generates the winners certificates and stores them to a file
        ///
        /// The file path is returned
        /// </summary>
        /// </summary>
        /// <param name="name"></param>
        /// <param name="rank"></param>
        /// <param name="tournamentname"></param>
        /// <param name="place"></param>
        /// <param name="date"></param>
        /// <returns>Path to generated certificate</returns>
        public static XpsDocument Generate(string name, int rank, string tournamentname, string place, string date)
        {
            Word.Application wApp = new Word.Application();
            wApp.Visible = false;

            Word.Documents wDocs        = wApp.Documents;
            object         missing      = System.Reflection.Missing.Value;
            string         templatePath = AppDomain.CurrentDomain.BaseDirectory + @"WinnerCertificatesTemplate\Urkunde_v2_final.docm";

            Word.Document wDoc = wDocs.Open(templatePath,
                                            missing,
                                            ReadOnly: false,
                                            Visible: false,
                                            Revert: false);
            wApp.WindowState = WdWindowState.wdWindowStateMinimize;
            wDoc.Activate();

            Word.Bookmarks wBookmarks = wDoc.Bookmarks;
            Word.Bookmark  wBookmark  = wBookmarks["TournamentName"];
            Word.Range     wRange     = wBookmark.Range;
            wRange.Text = tournamentname;

            Word.Bookmark wBookmark2 = wBookmarks["Name"];
            Word.Range    wRange2    = wBookmark2.Range;
            wRange2.Text = name;

            Word.Bookmark wBookmark3 = wBookmarks["Rank"];
            Word.Range    wRange3    = wBookmark3.Range;
            wRange3.Text = rank.ToString();

            Word.Bookmark wBookmark4 = wBookmarks["Place"];
            Word.Range    wRange4    = wBookmark4.Range;
            wRange4.Text = place;

            Word.Bookmark wBookmark5 = wBookmarks["Date"];
            Word.Range    wRange5    = wBookmark5.Range;
            wRange5.Text = date;

            string convertedXpsDoc = string.Concat(Path.GetTempPath(), "\\", Guid.NewGuid().ToString(), ".xps");

            wDoc.SaveAs(convertedXpsDoc, WdSaveFormat.wdFormatXPS);
            XpsDocument xpsDocument = new XpsDocument(convertedXpsDoc, FileAccess.Read);

            wDoc.Close(SaveChanges: false);
            wApp.Quit();

            return(xpsDocument);
        }
Exemplo n.º 8
0
    protected void Button4_Click(object sender, EventArgs e)
    {
        object o      = Missing.Value;
        object oFalse = false;
        object oTrue  = true;

        Word._Application app  = null;
        Word.Documents    docs = null;
        Word.Document     doc  = null;

        object path = @"C:\pru\otro.doc";

        try
        {
            app               = new Word.Application();
            app.Visible       = true;
            app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

            docs = app.Documents;
            //doc = docs.Open(ref path, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
            // segundo doc = docs.Open(ref path, ref o, false, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
            //doc = docs.Open(ref path, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

            doc = docs.Open(ref path, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

            doc.Activate();
        }
        finally
        {
            if (doc != null)
            {
                Marshal.FinalReleaseComObject(doc);
            }

            if (docs != null)
            {
                Marshal.FinalReleaseComObject(docs);
            }

            if (app != null)
            {
                Marshal.FinalReleaseComObject(app);
            }
        }
    }
Exemplo n.º 9
0
        //private Dictionary<string, string> Bookmarks = null;

        public WordTemplate(string templatePath)
        {
            this.Type         = TemplateType.WordTemplate;
            this.TemplatePath = templatePath;

            oWord = new Application();
            oDoc  = new Document();

            object readOnly  = false;
            object isVisible = false;
            object oTemplate = TemplatePath;

            Microsoft.Office.Interop.Word.Documents oDocTmp = oWord.Documents;
            oWord.Visible = false;

            try
            {
                oDoc = oDocTmp.Open(ref oTemplate,
                                    ref _missing,
                                    ref readOnly,
                                    ref _missing,
                                    ref _missing,
                                    ref _missing,
                                    ref _missing,
                                    ref _missing,
                                    ref _missing,
                                    ref _missing,
                                    ref _missing,
                                    ref isVisible,
                                    ref _missing,
                                    ref _missing,
                                    ref _missing,
                                    ref _missing);
            }
            catch (Exception ex)
            {
                this.Dispose();
                throw new Exception("Не удалось открыть документ.\r\n" + ex.Message);
            }
            oBookmarks = oDoc.Bookmarks;
        }
Exemplo n.º 10
0
        public override void Convert(string inputFile, string outputFile)
        {
            if (!File.Exists(inputFile))
            {
                throw new ConvertException("文件不存在!");
            }

            try
            {
                // 打开文档
                Word.Document doc = _docs.Open(inputFile);

                // 转换文档
                doc.ExportAsFixedFormat(outputFile, Word.WdExportFormat.wdExportFormatPDF);

                // 关闭文档
                Close(doc);
            }
            catch (Exception e)
            {
                // 打开、转换文档失败
                throw new ConvertException(e);
            }
        }
Exemplo n.º 11
0
    protected void Button2_Click(object sender, EventArgs e)
    {
        //Word.Application objWordApp;
        //objWordApp = new Word.Application();
        //Word.Document objDoc;
        //string rng = "Homero 213";
        //// Open an existing document.
        //objWordApp.Documents.Open("C:\\envio\\Muestra.docx");
        //objDoc = objWordApp.ActiveDocument;
        //// Find and replace some text.
        //objDoc.Content.Find.Execute("<Address>", rng, Word.WdReplace.wdReplaceAll);
        //// Save and close the document.
        //objWordApp.Documents.Save();
        //objWordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
        ////objWordApp.Quit();
        //objWordApp = null;

        object o      = Missing.Value;
        object oFalse = false;
        object oTrue  = true;

        Word._Application app  = null;
        Word.Documents    docs = null;
        Word.Document     doc  = null;

        object path = @"C:\pru\otrox.doc";

        try
        {
            app               = new Word.Application();
            app.Visible       = false;
            app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

            docs = app.Documents;
            //doc = docs.Open(ref path, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
            // segundo doc = docs.Open(ref path, ref o, false, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);

            doc = docs.Open(ref path, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);


            doc.Activate();

            foreach (Word.Range range in doc.StoryRanges)
            {
                Word.Find find       = range.Find;
                object    findText   = "$cliente_representante_legal;";
                object    replacText = "Espergencio Rocha Carreño";
                object    replace    = Word.WdReplace.wdReplaceAll;
                object    findWrap   = Word.WdFindWrap.wdFindContinue;

                find.Execute(ref findText, ref o, ref o, ref o, ref oFalse, ref o,
                             ref o, ref findWrap, ref o, ref replacText,
                             ref replace, ref o, ref o, ref o, ref o);

                Marshal.FinalReleaseComObject(find);
                Marshal.FinalReleaseComObject(range);
            }
            doc.SaveAs2(@"C:\pru\Modif.doc");
            //doc.Save();
            ((Word._Document)doc).Close(ref o, ref o, ref o);
            app.Quit(ref o, ref o, ref o);
        }
        finally
        {
            if (doc != null)
            {
                Marshal.FinalReleaseComObject(doc);
            }

            if (docs != null)
            {
                Marshal.FinalReleaseComObject(docs);
            }

            if (app != null)
            {
                Marshal.FinalReleaseComObject(app);
            }
        }
    }
Exemplo n.º 12
0
        /// <summary>
        /// WordファイルをPDFとして保存します。
        /// </summary>
        /// <param name="wordFilePathName">Wordファイルのパス付きファイル名。</param>
        /// <param name="saveAsPathName">保存するPDFのパス付きファイル名。</param>
        /// <remarks>
        /// <para>
        /// Word 2013がインストールされている必要があります。
        /// </para>
        /// </remarks>
        public static void SaveAsPdf(string wordFilePathName, string saveAsPathName)
        {
            // Word 2013がインストールされている必要があります。
            MSWord.ApplicationClass application = null;
            MSWord.Documents        documents   = null;
            MSWord.DocumentClass    document    = null;

            // refキーワードと共に渡すので、変数である必要がある。
            object missing = System.Type.Missing;

            try
            {
                application = new MSWord.ApplicationClass();

                /*
                 * application.Documents.Open(...は、Documentsオブジェクトの解放処理ができないので不可。
                 * 必ず変数経由でComRelease.FinalReleaseComObjectsを呼び出すこと。
                 */
                documents = application.Documents;

                object filePathName = wordFilePathName;
                object ReadOnly     = true;
                object Visible      = false;
                document = (MSWord.DocumentClass)documents.Open(
                    ref filePathName, ref missing, ref ReadOnly, ref missing, ref missing
                    , ref missing, ref missing, ref missing, ref missing, ref missing
                    , ref missing, ref Visible, ref missing, ref missing, ref missing, ref missing);

                // ExportAsFixedFormatのパラメータは以下を参照
                // http://msdn.microsoft.com/ja-jp/library/microsoft.office.tools.word.document.exportasfixedformat.aspx
                // http://msdn.microsoft.com/en-us/library/bb412305.aspx
                document.ExportAsFixedFormat(
                    saveAsPathName,
                    MSWord.WdExportFormat.wdExportFormatPDF,
                    false,
                    MSWord.WdExportOptimizeFor.wdExportOptimizeForPrint,
                    MSWord.WdExportRange.wdExportAllDocument,
                    0,
                    0,
                    MSWord.WdExportItem.wdExportDocumentWithMarkup,
                    true,
                    true,
                    MSWord.WdExportCreateBookmarks.wdExportCreateWordBookmarks,
                    true,
                    true,
                    false,
                    ref missing);
            }
            finally
            {
                if (document != null)
                {
                    try
                    {
                        document.Close(ref missing, ref missing, ref missing);
                    }
                    catch { }
                }
                if (application != null)
                {
                    try
                    {
                        application.Quit(ref missing, ref missing, ref missing);
                    }
                    catch { }
                }
                Com.ComRelease.FinalReleaseComObjects(document, documents, application);
            }
        }
Exemplo n.º 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();
            }
        }
Exemplo n.º 14
0
        public string GetWordFileDataMethod(string fileName, out string output1, out string output2,
                                            out string output3, out string output4, out string output5,
                                            out string output6, out string output7, out string output8,
                                            out string output9, out string output10, out string output11,
                                            out string output12, out string output13, out string output14,
                                            out string output15, out string output16)
        {
            Microsoft.Office.Interop.Word.Application app  = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Documents   docs = app.Documents;
            Microsoft.Office.Interop.Word.Document    doc  = docs.Open(fileName, ReadOnly: true);

            Microsoft.Office.Interop.Word.Table t1     = doc.Tables[1];
            Microsoft.Office.Interop.Word.Range r1     = t1.Range;
            Microsoft.Office.Interop.Word.Cells cells1 = r1.Cells;

            Microsoft.Office.Interop.Word.Table t2     = doc.Tables[2];
            Microsoft.Office.Interop.Word.Range r2     = t2.Range;
            Microsoft.Office.Interop.Word.Cells cells2 = r2.Cells;



            //convert tables to text to get rid of bullet points at the end of text fields
            Regex rg = new Regex("^[A-Za-z0-9/$ !|\\[]{}%&()]$");//regex filter on output text accepting characters alphanumeric and /


            Regex rgg = new Regex("^[A-Za-z0-9/$ .!|\\[]{}%&()]$");//regex filter on output text accepting characters alphanumeric and /

            //if (!rg.IsMatch(cells1[2].Range.Text))
            //{
            //    string employerName = "";
            //}
            //else
            //{
            //    string employerName = rg.Replace(cells1[2].Range.Text, "");
            //}

            //Table 1


            string employerName         = rg.Replace(cells1[2].Range.Text, "");
            string employerID           = rg.Replace(cells1[4].Range.Text, "");
            string region               = rg.Replace(cells1[6].Range.Text, "");
            string segment              = rg.Replace(cells1[8].Range.Text, "");
            string benefitEffectiveDate = rg.Replace(cells1[10].Range.Text, "");
            string currentProducts      = rg.Replace(cells1[12].Range.Text, "");
            string addedProducts        = rg.Replace(cells1[14].Range.Text, "");
            string newImpFlag           = rg.Replace(cells1[16].Range.Text, "");
            string IM_AM       = rg.Replace(cells1[18].Range.Text, "");
            string impDeadline = rg.Replace(cells1[20].Range.Text, "");
            string sftpCreds   = "";

            //Remove MS Word table1 character '•' from the ends of all the text fields

            employerName         = employerName.Remove(employerName.Length - 1, 1);
            employerID           = employerID.Remove(employerID.Length - 1, 1);
            region               = region.Remove(region.Length - 1, 1);
            segment              = segment.Remove(segment.Length - 1, 1);
            benefitEffectiveDate = benefitEffectiveDate.Remove(benefitEffectiveDate.Length - 1, 1);
            currentProducts      = currentProducts.Remove(currentProducts.Length - 1, 1);
            addedProducts        = addedProducts.Remove(addedProducts.Length - 1, 1);
            newImpFlag           = newImpFlag.Remove(newImpFlag.Length - 1, 1);
            IM_AM       = IM_AM.Remove(IM_AM.Length - 1, 1);
            impDeadline = impDeadline.Remove(impDeadline.Length - 1, 1);

            //get rid of carraige return in all fields

            employerName         = employerName.TrimEnd('\r', '\n');
            employerID           = employerID.TrimEnd('\r', '\n');
            region               = region.TrimEnd('\r', '\n');
            segment              = segment.TrimEnd('\r', '\n');
            benefitEffectiveDate = benefitEffectiveDate.TrimEnd('\r', '\n');
            currentProducts      = currentProducts.TrimEnd('\r', '\n');
            addedProducts        = addedProducts.TrimEnd('\r', '\n');
            newImpFlag           = newImpFlag.TrimEnd('\r', '\n');
            IM_AM       = IM_AM.TrimEnd('\r', '\n');
            impDeadline = impDeadline.TrimEnd('\r', '\n');
            sftpCreds   = sftpCreds.TrimEnd('\r', '\n');



            //added field to the implementation table
            if (t1.Rows.Count == 11)
            {
                sftpCreds = rg.Replace(cells1[22].Range.Text, "");
            }
            else if (t1.Rows.Count == 10)
            {
                sftpCreds = string.Empty;
            }



            output1  = employerName;
            output2  = employerID;
            output3  = region;
            output4  = segment;
            output5  = benefitEffectiveDate;
            output6  = currentProducts;
            output7  = addedProducts;
            output8  = newImpFlag;
            output9  = IM_AM;
            output10 = impDeadline;
            output11 = sftpCreds;



            //Table 2


            string contactName        = rgg.Replace(cells2[6].Range.Text, "");
            string contactphoneNumber = rgg.Replace(cells2[7].Range.Text, "");
            string contactEmail       = rgg.Replace(cells2[8].Range.Text, "");
            string contactType        = rgg.Replace(cells2[9].Range.Text, "");
            string fileType           = rgg.Replace(cells2[10].Range.Text, "");

            //Remove MS Word table2 character '•' from the ends of all the text fields

            contactName        = contactName.Remove(contactName.Length - 1, 1);
            contactphoneNumber = contactphoneNumber.Remove(contactphoneNumber.Length - 1, 1);
            contactEmail       = contactEmail.Remove(contactEmail.Length - 1, 1);
            contactType        = contactType.Remove(contactType.Length - 1, 1);
            fileType           = fileType.Remove(fileType.Length - 1, 1);


            //assign output variables
            output12 = contactName;
            output13 = contactphoneNumber;
            output14 = contactEmail;
            output15 = contactType;
            output16 = fileType;



            GetterSetterString getData = new GetterSetterString();

            getData.DataValue = employerName;


            //docs.Close();
            app.Quit();


            return(""); //This is the output door for the outputs to go through
        }