Exemplo n.º 1
0
        public virtual bool SetDocumentProperty <T>(string propertyName, T value)
        {
            var propertiesPart = GetCustomFilePropertiesPart();

            if (propertiesPart != null)
            {
                var props = propertiesPart.Properties;
                var prop  = props.OfType <CustomDocumentProperty>().FirstOrDefault(p => p.Name.Value == propertyName);
                if (prop == null)
                {
                    prop = new CustomDocumentProperty
                    {
                        Name       = propertyName,
                        FormatId   = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", // siehe https://msdn.microsoft.com/en-us/library/office/hh674468.aspx
                        PropertyId = props.OfType <CustomDocumentProperty>().Max(prp => (int)prp.PropertyId) + 1
                    };
                    propertiesPart.Properties.AppendChild(prop);
                }
                //prop.SetProperty(value);
                props.Save();

                // Create object to update fields on open
                var settingsPart = GetDocumentSettingsPart();
                if (settingsPart != null)
                {
                    var updateFields = new UpdateFieldsOnOpen {
                        Val = new OnOffValue(true)
                    };
                    settingsPart.Settings.PrependChild(updateFields);
                    settingsPart.Settings.Save();
                }
                return(true);
            }
            return(false);
        }
Exemplo n.º 2
0
        //public static void AddSettingsTable(WordprocessingDocument doc, List<CCOLElement> elements)
        //{
        //    Table table = new Table();
        //
        //    TableProperties props = new TableProperties(
        //        new TableBorders(
        //        new TopBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },
        //        new BottomBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },
        //        new LeftBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },
        //        new RightBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },
        //        new InsideHorizontalBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },
        //        new InsideVerticalBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 }),
        //        new TableWidth() { Type = TableWidthUnitValues.Pct, Width = $"{100 * 50}" });
        //
        //    table.AppendChild(props);
        //
        //    AddRowToTable(
        //            table,
        //            new[] { "Type", "Naam", "Instelling", "Commentaar" },
        //            new[] { 14, 14, 14, 58 });
        //
        //    foreach (var e in elements)
        //    {
        //        AddRowToTable(
        //            table,
        //            new[] { e.Type.ToString(), e.Naam, e.Instelling.ToString(), e.Commentaar },
        //            new[] { 14, 14, 14, 58 });
        //    }
        //
        //    doc.MainDocumentPart.Document.Body.Append(new Paragraph(new Run(table)));
        //}



        public static void SetDirtyFlag(WordprocessingDocument doc)
        {
            DocumentSettingsPart settingsPart = doc.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();
            UpdateFieldsOnOpen   updateFields = new UpdateFieldsOnOpen();

            updateFields.Val = new OnOffValue(true);
            settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);
            settingsPart.Settings.Save();
        }
Exemplo n.º 3
0
        public void SetUpdateOnOpen(WordprocessingDocument xmlDoc)
        {
            //Open Word Setting File
            DocumentSettingsPart settingsPart = xmlDoc.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();
            //Update Fields
            UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen();

            updateFields.Val = new OnOffValue(true);

            settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);
            settingsPart.Settings.Save();
        }
Exemplo n.º 4
0
        /// <summary>
        /// The field values in the word doc need to be update in the property settings object of the word doc. The questions
        /// have 'keys' which we are using with MappingsEnum to know how update with the value from the IntakeForms. Then we
        /// explicitly ask the user to verify the fields are to be updated when opening the word doc.
        /// </summary>
        /// <param name="intakeForms"></param>
        /// <param name="doc"></param>
        private void UpdateValuesInWordDocsCustomProperties(
            WordprocessingDocument doc,
            IntakeFormModel intakeForm,
            PatientModel patient,
            PhysicianModel physician,
            ICollection <SignatureModel> signatures)
        {
            // Get all question's with a key, then gather the value as all answers comma delimited
            var intakeFromKeys = intakeForm.Questions
                                 .Where(r => !string.IsNullOrEmpty(r.Key))
                                 .Select(y => new KeyValuePair <string, string>(y.Key.ToUpper(), y.Answers.Select(z => z.Text)
                                                                                .Aggregate((c, n) => $"{c},{n}"))).ToList();

            intakeFromKeys.AddRange(GetPatientKeys(patient));
            intakeFromKeys.AddRange(GetAllCodes(intakeForm));
            intakeFromKeys.AddRange(GetPhysicanKeys(physician));
            intakeFromKeys.AddRange(GetSignature(signatures.First())); // just use the first signature for now since IP/Creation should be identicalish
            intakeFromKeys.AddRange(GetDrNotes(intakeForm.PhysicianNotes ?? ""));

            //This will update all of the custom properties that are used in the word doc.
            //Again, the fields are update in the document settings, but the downloading user
            //will need to approve the update for any fields.

            //https://docs.microsoft.com/en-us/office/open-xml/how-to-set-a-custom-property-in-a-word-processing-document
            Properties properties = doc.CustomFilePropertiesPart.Properties;

            foreach (MappingEnums propertyEnum in Enum.GetValues(typeof(MappingEnums)))
            {
                var item = (CustomDocumentProperty)properties
                           .FirstOrDefault(x => ((CustomDocumentProperty)x).Name.Value.Equals(propertyEnum.ToString()));
                if (item != null)
                {
                    //If a key doesn't exist, you could see an empty value stuffed into the word doc
                    var val = intakeFromKeys.FirstOrDefault(x => x.Key == propertyEnum.ToString().ToUpper()).Value ?? "N/A";
                    item.VTLPWSTR = new VTLPWSTR(val);
                }
            }

            properties.Save();

            //The docx is using Custom Properties and above we are updating the custom property values,
            //however there is no way (that I have found) to programatically updated all of the fields
            //that are using the custom properties without requiring the downloader to
            DocumentSettingsPart settingsPart = doc.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();
            var updateFields = new UpdateFieldsOnOpen
            {
                Val = new OnOffValue(true)
            };

            settingsPart.Settings.PrependChild(updateFields);
            settingsPart.Settings.Save();
            doc.Save();
        }
        public static WordprocessingDocument UpdatePropertiesOnOpening(this WordprocessingDocument wordDoc)
        {
            DocumentSettingsPart settingsPart = wordDoc.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();

            //Update Fields
            UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen();

            updateFields.Val = new OnOffValue(true);

            settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);
            settingsPart.Settings.Save();

            return(wordDoc);
        }
Exemplo n.º 6
0
        public static DocX CreateDocA(DocX template, JIUViewModel model, string source)
        {
            string sym = model.Sym.ToString();

            string[] SymStr   = sym.Split('/');
            string[] sym1     = SymStr.Skip(1).ToArray();
            string   Fsym     = String.Join("/", sym1);
            int      yearppos = 0;


            //document Language "Section"
            string Ftlang = "";

            Ftlang = Tlanguage(model.lang_ID);
            //ORiginal Language
            string Folang = "";
            // Folang = Olanguage1(model.Olang_ID);


            string FPname = "[Prepared By]";

            //Typist
            if (!String.IsNullOrEmpty(model.Pname))
            {
                //string[] arr = model.Pname.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                //FPname = "";
                //for (int x = 0; x < arr.Length-1; x++)
                //{

                //    FPname = FPname+ arr[x] +"\n";

                //}
                //int xs = arr.Length;
                //FPname = FPname + arr[xs-1];
                FPname = model.Pname.ToString();
            }
            //Novacode.Formatting prepared = new Novacode.Formatting();
            //prepared.Italic = true;
            //prepared.Bold = true;
            //prepared.Size=14;


            // template.ReplaceText("Pname", FPname,false,RegexOptions.None,prepared);

            //Agenda Title
            string FJtitle = "[Title]";

            if (!String.IsNullOrEmpty(model.JTitle))
            {
                FJtitle = model.JTitle.ToString();
            }
            ///
            //Year Jdate

            string structure = model.structure.ToString();

            string[] str    = structure.Split('/');
            string   FJdate = "[YEAR]";

            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == "&")
                {
                    yearppos = i;
                    FJdate   = SymStr[i];
                }
            }

            //create barcode
            string Fbar = "";

            if (!String.IsNullOrEmpty(model.Gdoc))
            {
                Fbar = model.Gdoc.ToString();
                Fbar = "*" + Fbar + "*";
            }

            string gdoc   = "";
            string Fgdocf = "";

            if (!String.IsNullOrEmpty(model.Gdoc))
            {
                gdoc   = model.Gdoc.ToString();
                gdoc   = gdoc.Insert(2, "-");
                Fgdocf = gdoc;
            }



            DateTime xxx = DateTime.Now;



            template.AddCustomProperty(new CustomProperty("sym1", Fsym));

            template.AddCustomProperty(new CustomProperty("symh", sym));
            //template.AddCustomProperty(new CustomProperty("symh1", sym));
            //template.AddCustomProperty(new CustomProperty("symh2", sym));

            // template.ReplaceText(sym, sym, false, RegexOptions.IgnoreCase);



            template.AddCustomProperty(new CustomProperty("jdate", FJdate));
            //   template.ReplaceText("sdate", Fsdate, false, RegexOptions.IgnoreCase);


            template.AddCustomProperty(new CustomProperty("olang", Ftlang));
            template.AddCustomProperty(new CustomProperty("gdoc", gdoc));
            template.AddCustomProperty(new CustomProperty("gdoc1", gdoc));
            // template.ReplaceText("gdoc", gdoc, false, RegexOptions.IgnoreCase);

            template.AddCustomProperty(new CustomProperty("gdocf", Fgdocf));
            template.AddCustomProperty(new CustomProperty("test", Fgdocf));
            //template.AddCustomProperty(new CustomProperty("gdocf1", Fgdocf));
            //template.AddCustomProperty(new CustomProperty("gdocf2", Fgdocf));
            // template.ReplaceText("gdocf", Fgdocf, false, RegexOptions.IgnoreCase);

            template.AddCustomProperty(new CustomProperty("tlang", ""));
            // template.ReplaceText("tlang", Ftlang, false, RegexOptions.IgnoreCase);

            template.AddCustomProperty(new CustomProperty("jtitle", FJtitle));
            // template.ReplaceText("atitle", Fatitle, false, RegexOptions.IgnoreCase);

            template.AddCustomProperty(new CustomProperty("Pname", FPname));
            // template.ReplaceText("stitle", Fstitle, false, RegexOptions.IgnoreCase);



            template.AddCustomProperty(new CustomProperty("bar", Fbar));
            //   template.ReplaceText("bar", Fbar, false, RegexOptions.IgnoreCase);

            template.AddCustomProperty(new CustomProperty("Date-Generated", xxx));
            template.AddCustomProperty(new CustomProperty("Org", "JIU"));
            template.AddCustomProperty(new CustomProperty("Entity", "JIU"));
            template.AddCustomProperty(new CustomProperty("doctype", "Main"));
            template.AddCustomProperty(new CustomProperty("category", "Report"));

            using (WordprocessingDocument
                   document = WordprocessingDocument.Open(source, true))

            {
                DocumentSettingsPart settingsPart = document.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();



                // Create object to update fields on open


                UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen();

                updateFields.Val = new DocumentFormat.OpenXml.OnOffValue(true);



                // Insert object into settings part.


                settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);

                settingsPart.Settings.Save();


                document.MainDocumentPart.Document.RemoveAllChildren <BookmarkStart>();
                document.MainDocumentPart.Document.RemoveAllChildren <BookmarkEnd>();
            }

            return(template);
        }
Exemplo n.º 7
0
        public override void Write()
        {
            ExportFileName = PopulatedName(ExportFileName);
            if (!String.IsNullOrWhiteSpace(ExportFileName))
            {
                DocProperties["FileName"]   = ExportFileName;
                DocProperties["TableCount"] = _dataSet.Tables.Count.ToString();
                if (PopulatePropertiesOnly)
                {
                    if (_dataSet != null)
                    {
                        foreach (DataTable dTable in _dataSet.Tables)
                        {
                            if (dTable.Rows.Count > 0)
                            {
                                foreach (DataColumn dColumn in dTable.Columns)
                                {
                                    DocProperties[dColumn.ColumnName] = dTable.Rows[0][dColumn].ToString();
                                }
                            }
                        }
                    }
                }
                switch (DestinationType)
                {
                case OfficeFileType.WordDocument:
                    WordprocessingDocument doc;
                    if (File.Exists(TemplateFileName))
                    {
                        doc = WordprocessingDocument.CreateFromTemplate(TemplateFileName);
                        doc = (WordprocessingDocument)doc.SaveAs(ExportFileName);
                    }
                    else
                    {
                        doc = WordprocessingDocument.Create(ExportFileName, WordprocessingDocumentType.Document);
                    }
                    CustomFilePropertiesPart customProp = doc.CustomFilePropertiesPart;
                    if (customProp == null)
                    {
                        customProp = doc.AddCustomFilePropertiesPart();
                    }
                    SetFileProperties(customProp);

                    MainDocumentPart mainDoc = doc.MainDocumentPart;
                    if (mainDoc == null)
                    {
                        mainDoc = doc.AddMainDocumentPart();
                    }

                    DocumentSettingsPart settingsPart = mainDoc.GetPartsOfType <DocumentSettingsPart>().First();
                    UpdateFieldsOnOpen   updateFields = new UpdateFieldsOnOpen
                    {
                        Val = new OnOffValue(true)
                    };
                    settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);
                    settingsPart.Settings.Save();

                    if (!PopulatePropertiesOnly)
                    {
                        if (mainDoc.Document == null)
                        {
                            mainDoc.Document = new word.Document();
                        }
                        word.Body body       = new word.Body();
                        bool      firstTable = true;
                        foreach (DataTable dt in _dataSet.Tables)
                        {
                            if (!firstTable)
                            {
                                body.Append(GetPageBreak());
                            }
                            else
                            {
                                firstTable = false;
                            }
                            body.Append(GetParagraph(dt.TableName));
                            body.Append(GetWordTable(dt));
                        }
                        mainDoc.Document.Append(body);
                    }
                    mainDoc.Document.Save();
                    doc.Dispose();
                    break;

                case OfficeFileType.ExcelWorkbook:
                    SpreadsheetDocument spreadSheet;
                    if (File.Exists(TemplateFileName))
                    {
                        spreadSheet = SpreadsheetDocument.CreateFromTemplate(TemplateFileName);
                        spreadSheet = (SpreadsheetDocument)spreadSheet.SaveAs(ExportFileName);
                    }
                    else
                    {
                        spreadSheet = SpreadsheetDocument.Create(ExportFileName, SpreadsheetDocumentType.Workbook);
                        spreadSheet.Save();
                    }
                    using (SpreadsheetDocument workbook = spreadSheet)
                    {
                        CustomFilePropertiesPart excelCustomProp = workbook.AddCustomFilePropertiesPart();
                        SetFileProperties(excelCustomProp);

                        if (workbook.WorkbookPart == null)
                        {
                            workbook.AddWorkbookPart();
                        }
                        if (workbook.WorkbookPart.Workbook == null)
                        {
                            workbook.WorkbookPart.Workbook = new excel.Workbook();
                        }
                        if (workbook.WorkbookPart.Workbook.Sheets == null)
                        {
                            workbook.WorkbookPart.Workbook.Sheets = new excel.Sheets();
                        }
                        excel.Sheets sheets = workbook.WorkbookPart.Workbook.Sheets;
                        foreach (DataTable table in _dataSet.Tables)
                        {
                            excel.SheetData sheetData = null;
                            WorksheetPart   sheetPart = null;
                            excel.Sheet     sheet     = null;
                            foreach (OpenXmlElement element in sheets.Elements())
                            {
                                if (element is Sheet)
                                {
                                    sheet = (Sheet)element;
                                    if (sheet.Name.Value.Equals(table.TableName, StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        //Assign the sheetPart
                                        sheetPart = (WorksheetPart)workbook.WorkbookPart.GetPartById(sheet.Id.Value);
                                        sheetData = sheetPart.Worksheet.GetFirstChild <SheetData>();
                                        break;
                                    }
                                }
                                sheet = null;
                            }

                            if (sheet == null)
                            {
                                sheetPart           = workbook.WorkbookPart.AddNewPart <WorksheetPart>(); //Create a new WorksheetPart
                                sheetData           = new excel.SheetData();                              //create a new SheetData
                                sheetPart.Worksheet = new excel.Worksheet(sheetData);                     /// Create a new Worksheet with the sheetData and link it to the sheetPart...

                                string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);     //get the ID of the sheetPart.
                                sheet = new excel.Sheet()
                                {
                                    Id = relationshipId, SheetId = 1, Name = table.TableName
                                };                        //create a new sheet
                                sheets.Append(sheet);     //append the sheet to the sheets.
                            }

                            List <String> columns = new List <string>();
                            foreach (System.Data.DataColumn column in table.Columns)
                            {
                                columns.Add(column.ColumnName);
                            }
                            if (PrintTableHeader)
                            {
                                excel.Row headerRow = new excel.Row();

                                foreach (string column in columns)
                                {
                                    excel.Cell cell = new excel.Cell
                                    {
                                        DataType  = excel.CellValues.String,
                                        CellValue = new excel.CellValue(GetColumnName(table.Columns[column]))
                                    };
                                    headerRow.AppendChild(cell);
                                }


                                sheetData.AppendChild(headerRow);
                            }

                            foreach (DataRow dsrow in table.Rows)
                            {
                                excel.Row newRow = new excel.Row();
                                foreach (String col in columns)
                                {
                                    excel.Cell cell = new excel.Cell
                                    {
                                        DataType  = excel.CellValues.String,
                                        CellValue = new excel.CellValue(dsrow[col].ToString())     //
                                    };
                                    newRow.AppendChild(cell);
                                }

                                sheetData.AppendChild(newRow);
                            }
                            sheetPart.Worksheet.Save();
                        }
                        workbook.WorkbookPart.Workbook.Save();
                        workbook.Save();
                        workbook.Close();
                    }

                    break;
                }
            }
        }
Exemplo n.º 8
0
        public byte[] Export()
        {
            var bytes = File.ReadAllBytes(tempPath);

            using (var ms = new MemoryStream())
            {
                ms.Write(bytes, 0, bytes.Length);
                using (var doc = WordprocessingDocument.Open(ms, true))
                {
                    // 书签名称
                    mainDocumentPart = doc.MainDocumentPart;
                    var body         = doc.MainDocumentPart.Document.Body;
                    var settingsPart = mainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();

                    // Create object to update fields on open
                    var updateFields = new UpdateFieldsOnOpen();
                    updateFields.Val = new OnOffValue(true);

                    // Insert object into settings part.
                    settingsPart.Settings.PrependChild(updateFields);
                    settingsPart.Settings.Save();

                    IDictionary <string, object> main = null;
                    WordTag currentTag = null;
                    if (ds.ContainsKey("main"))
                    {
                        main = ds["main"].First();
                    }

                    // 遍历根级段落
                    var current = body.FirstChild;
                    do
                    {
                        var bStart = HasBookMark(current);
                        if (currentTag == null && bStart != null)
                        {
                            // 是书签的话,加入列表
                            currentTag = new WordTag {
                                Bookmark = bStart
                            };
                        }
                        else if (current is BookmarkEnd bEnd && currentTag != null &&
                                 bEnd.Id == currentTag.Bookmark.Id)
                        {
                            // 此处扩展
                            var bookmark  = currentTag.Bookmark.Name;
                            var dataset   = ds[props.GetValue($"{bookmark}:dataset")];
                            var parentKey = props.GetNullValue($"{bookmark}:parent");
                            if (parentKey != null)
                            {
                                // 定义了父链字段
                                var parentVal = "";
                                if (parentKey.HasValue())
                                {
                                    parentVal = main.GetValue(parentKey, "");
                                }
                                dataset = dataset.Where(r =>
                                {
                                    var row = r as IDictionary <string, object>;
                                    return(row.GetValue("parentid", "") == parentVal);
                                });
                            }
                            ExpandBookmark(body, currentTag, bEnd, dataset);

                            // 设为非书签状态
                            bStart     = null;
                            currentTag = null;
                        }
                        else if (currentTag != null)
                        {
                            currentTag.Add(current);

                            var previous = current.PreviousSibling();
                            current.Remove();
                            current = previous;
                        }
                        else if (current is Table table)
                        {
                            ExpandTable(table, main);
                        }
                        else
                        {
                            ReplaceParagraph(current, main);
                        }

                        // 取下一对象
                        current = current.NextSibling();
                    }while (current != null);
                }

                return(ms.ToArray());
            }
Exemplo n.º 9
0
        public ActionResult PrictDoc(string doctext)
        {
            List <TemplateSectionVo> Grid = JsonConvert.DeserializeObject <List <TemplateSectionVo> >(doctext);
            //htmlString = "<h1 style='text-align: center;'><strong>Report</strong></h1>" + "<br>";
            string sourceFile = Server.MapPath(Path.Combine("/", "Themes/Template/PSURTemplate.dotx"));
            var    filename   = Path.GetFileNameWithoutExtension(sourceFile);

            destinationFile = Server.MapPath(Path.Combine("/", "Themes/DownloadDocs/" + "PBRER" + DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss") + ".docx"));
            try
            {
                // Create a copy of the template file and open the copy
                System.IO.File.Copy(sourceFile, destinationFile, true);
                WordprocessingDocument wordDoc =
                    WordprocessingDocument.Open(destinationFile, true);
                wordDoc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
                //marker for main document part
                var mainDocPart = wordDoc.MainDocumentPart;

                //Iterate through the paragraphs to find the bookmarks inside
                //load bookmarks
                var bookmarks = mainDocPart.Document.Body.Descendants <BookmarkStart>();

                for (int i = 0; i < Grid.Count; i++)
                {
                    //find our bookmark
                    string bookmarkname1 = Regex.Match(Grid[i].Section, @"(\d+.\d+.\d+.|\d+.\d+.|\d+.)").Value;
                    string bookmarkname  = bookmarkname1.Replace(".", "_");
                    //get to first element
                    if (bookmarkname1 == null || bookmarkname1 == "")
                    {
                        bookmarkname = Regex.Replace(Grid[i].Section, @"[\d+|.|\s]", "");
                    }
                    var bookmark = from bookmarkIndex in bookmarks where bookmarkIndex.Name == "BK_" + bookmarkname select bookmarkIndex;
                    if (bookmark.Count() > 0)
                    {
                        htmlString = "";
                        if (Grid[i].Template_Content != null)
                        {
                            htmlString = "<html>" + Grid[i].Template_Content.Replace("<table>", "<table border='1' style=' border-collapse: collapse; border: 1px solid black;width:100%;'>");
                        }
                        string UrlLink = new Uri(Request.Url, Url.Content("~")).AbsoluteUri + "ImageBrowser/Image";
                        string source  = "/ImageBrowser/Image";
                        string CON     = htmlString;
                        htmlString = CON.Replace(source, UrlLink);
                        OpenXmlElement elem = bookmark.First().Parent;
                        String         cid  = "chunkid_" + i;
                        MemoryStream   ms   = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(htmlString));
                        AlternativeFormatImportPart formatImportPart = wordDoc.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, cid);
                        formatImportPart.FeedData(ms);
                        AltChunk altChunk = new AltChunk();
                        altChunk.Id = cid;
                        elem.InsertAfterSelf <AltChunk>(altChunk);
                        elem.Remove();
                    }
                }
                DocumentSettingsPart settingsPart = mainDocPart.Document.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();
                // Create object to update fields on open
                UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen();
                updateFields.Val = new DocumentFormat.OpenXml.OnOffValue(true);
                // Insert object into settings part.
                settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);
                settingsPart.Settings.Save();
                wordDoc.Close();
                return(Json("Sucess"));
            }
            catch (Exception ex)
            {
                //string ErrorData = "Please Close the Word and try again";
                return(Json(ex.Message));
            }
            return(Json("Sucess"));
        }