Example #1
0
        private static void FillByTemplate(WordprocessingDocument doc, TemplateData template)
        {
            try
            {
                if (template != null)
                {
                    Body body = doc.MainDocumentPart.Document.Body;

                    FillTable(body.Descendants <Table>(), template.Tables);
                    FillShape(body.Descendants <WordprocessingShape>(), template.TextShapes);
                    foreach (HeaderPart headerPart in doc.MainDocumentPart.HeaderParts)
                    {
                        FillShape(headerPart.Header.Descendants <WordprocessingShape>(), template.HeaderTextShape);
                    }
                    foreach (FooterPart footerPart in doc.MainDocumentPart.FooterParts)
                    {
                        FillShape(footerPart.Footer.Descendants <WordprocessingShape>(), template.FooterTextShapes);
                    }

                    doc.Save();
                }
                doc.Close();
            }
            catch (Exception e)
            {
                doc.Close();
                throw e;
            }
        }
Example #2
0
 private static string[][] GetTextShapeValue(WordprocessingDocument doc, IEnumerable <Func <string, bool> > identifyByName)
 {
     string[][] ret = null;
     try
     {
         if (identifyByName != null && identifyByName.Any())
         {
             ret = new string[identifyByName.Count()][];
             int  i    = 0;
             Body body = doc.MainDocumentPart.Document.Body;
             foreach (Func <string, bool> identify in identifyByName)
             {
                 IEnumerable <string> v = GetTextShapeValue(body.Descendants <WordprocessingShape>(), identify);
                 foreach (HeaderPart headerPart in doc.MainDocumentPart.HeaderParts)
                 {
                     v = v.Concat(GetTextShapeValue(headerPart.Header.Descendants <WordprocessingShape>(), identify));
                 }
                 foreach (FooterPart footerPart in doc.MainDocumentPart.FooterParts)
                 {
                     v = v.Concat(GetTextShapeValue(footerPart.Footer.Descendants <WordprocessingShape>(), identify));
                 }
                 ret[i] = v.ToArray();
                 i++;
             }
         }
     }
     catch (Exception e)
     {
         doc.Close();
         throw e;
     }
     doc.Close();
     return(ret);
 }
        public override void SaveToDocument(string destination, string documentName)
        {
            MainDocumentPart     mainPart = document.MainDocumentPart;
            DocumentSettingsPart documentSettingsPart1 = mainPart.DocumentSettingsPart;

            //
            AttachedTemplate attachedTemplate1 = new AttachedTemplate()
            {
                Id = "relationId1"
            };

            documentSettingsPart1.Settings.Append(attachedTemplate1);

            documentSettingsPart1.AddExternalRelationship(
                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
                new Uri(TemplatePath, UriKind.Absolute),
                "relationId1");
            mainPart.Document.Save();

            document.Close();

            using (FileStream fs = new FileStream(Path.Combine(destination, documentName), FileMode.Create))
            {
#warning См. комментарий
                // Цитата со StackOverflow:
                // Use CopyTo instead, there is a bug in WriteTo which makes it fail to write the entire content of the buffer when the target stream does not support writing everything in one go.
                memory.WriteTo(fs);
            }

            memory.Close();
            IsDisposed = true;
        }
Example #4
0
 /// <summary>
 /// Close the file
 /// </summary>
 public void Close()
 {
     if (m_Document != null)
     {
         m_Document.Close();
     }
 }
        public static bool SearchWordContains(string filepath, string condition)
        {
            List <string> words = new List <string>();

            if (string.IsNullOrEmpty(filepath) || !File.Exists(filepath))
            {
                return(false);
            }
            WordprocessingDocument package = WordprocessingDocument.Open(filepath, true);
            OpenXmlElement         element = package.MainDocumentPart.Document.Body;

            if (element == null)
            {
                package.Close();
                return(false);
            }
            string innText = element.InnerText;

            string[] conditions = ParseCondition(condition);
            foreach (var cond in conditions)
            {
                if (innText.IndexOf(cond, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    package.Close();
                    return(true);
                }
            }
            package.Close();
            return(false);
        }
Example #6
0
        public override void Save(string path)
        {
            MainDocumentPart     mainPart = document.MainDocumentPart;
            DocumentSettingsPart documentSettingsPart1 = mainPart.DocumentSettingsPart;

#if templates_old
            AttachedTemplate attachedTemplate1 = new AttachedTemplate()
            {
                Id = "relationId1"
            };
            documentSettingsPart1.Settings.Append(attachedTemplate1);

            // На заметку: узнать подробнее про External Relationships в структуре OpenXML.
            // Пэ Эс: можно (и даже нужно) заполнять фигней. Если подставлять реальный URI, может повесить ворд.
            documentSettingsPart1.AddExternalRelationship(
                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
                new Uri(@"c:\foo\bar", UriKind.Absolute),
                "relationId1");
#endif

            mainPart.Document.Save();

            document.Close();

            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                memory.WriteTo(fs);
            }
            memory.Close();
            IsDisposed = true;
        }
Example #7
0
 /// <summary>
 /// Constructor (If Filename -> try open file)
 /// </summary>
 /// <param name="fileName">File name of docx document</param>
 /// <exception cref="System.ArgumentNullException">The exception that is thrown when a null reference is passed to a method that does not accept it as a valid argument.</exception>
 /// <exception cref="DocumentFormat.OpenXml.Packaging.OpenXmlPackageException">OpenXml exception class</exception>
 public WordEdit(string fileName = "")
 {
     if (fileName != "")
     {
         if (doc != null)
         {
             doc.Close();
         }
         isOpen = _open(fileName);
     }
 }
Example #8
0
 /// <summary>
 /// 輸出檔案(memory)
 /// </summary>
 public void Flush(string outputName)
 {
     outDoc.MainDocumentPart.Document.Save();
     outDoc.Close();
     //byte[] byteArray = outMem.ToArray();
     HttpContext.Current.Response.Clear();
     HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.GetEncoding("big5");
     HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + outputName + "\"");
     HttpContext.Current.Response.ContentType = "application/octet-stream";
     HttpContext.Current.Response.AddHeader("Content-Length", outMem.Length.ToString());
     HttpContext.Current.Response.BinaryWrite(outMem.ToArray());
     //this.Dispose();
 }
Example #9
0
        private static object[][] GetTable(WordprocessingDocument doc, IEnumerable <TemplateTable> tables)
        {
            List <object[]> rts = new List <object[]>();

            try
            {
                if (tables != null && tables.Any())
                {
                    IEnumerable <Table> docTables = doc.MainDocumentPart.Document.Body.Descendants <Table>();
                    foreach (Table table in docTables)
                    {
                        TableRow[] rows = table.Elements <TableRow>()?.ToArray();
                        if (rows != null && rows.Length > 1)
                        {
                            string[] header = rows[0].Elements <TableCell>().Select(x => x.InnerText?.Trim(GetControls())).ToArray();
                            int      cc     = header.Length;
                            foreach (TemplateTable tt in tables)
                            {
                                if (tt.StartRow < rows.Length && tt.IsEqual(header))
                                {
                                    List <object> rt = new List <object>();
                                    for (int r = tt.StartRow; r < rows.Length; r++)
                                    {
                                        string[] row  = rows[r].Elements <TableCell>().Select(x => x.InnerText?.Trim(GetControls())).ToArray();
                                        object   item = tt.ToItem(row);
                                        if (item != null)
                                        {
                                            rt.Add(item);
                                        }
                                    }
                                    if (rt.Count > 0)
                                    {
                                        rts.Add(rt.ToArray());
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                doc.Close();
                throw e;
            }
            doc.Close();
            return(rts.Count > 0 ? rts.ToArray() : null);
        }
        public void OpenDocument(string filepath)
        {
            WordprocessingDocument wordprocessingDocument =
                WordprocessingDocument.Open(filepath, true);

            wordprocessingDocument.Close();
        }
Example #11
0
        public void OpenAndSearchDocument(string docxFilePath, string xmlFilePath)
        {
            //split XML Read
            var   xml = File.ReadAllText(xmlFilePath);
            Split splitXml;

            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Split));
                splitXml = (Split)serializer.Deserialize(stream);
            }

            // Open a WordprocessingDocument for editing using the filepath.
            WordprocessingDocument wordprocessingDocument =
                WordprocessingDocument.Open(docxFilePath, true);

            // Assign a reference to the existing document body.
            Body             body    = wordprocessingDocument.MainDocumentPart.Document.Body;
            MarkerWordMapper mapping = new MarkerWordMapper(DocumentName, splitXml, body);

            DocumentElements = mapping.Run();

            // Close the handle explicitly.
            wordprocessingDocument.Close();
        }
Example #12
0
        public void HtmlToWordPartial(string html, string destinationFileName)
        {
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(destinationFileName, WordprocessingDocumentType.Document))
            {
                string altChunkId = "myId";

                MainDocumentPart mainPart = wordDocument.MainDocumentPart;
                if (mainPart == null)
                {
                    mainPart = wordDocument.AddMainDocumentPart();
                    new DocumentFormat.OpenXml.Wordprocessing.Document(new Body()).Save(mainPart);
                }
                MemoryStream ms = new MemoryStream(new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(html)).ToArray());

                // Uncomment the following line to create an invalid word document.
                // MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<h1>HELLO</h1>"));

                // Create alternative format import part.
                AlternativeFormatImportPart formatImportPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId);
                //ms.Seek(0, SeekOrigin.Begin);

                // Feed HTML data into format import part (chunk).
                formatImportPart.FeedData(ms);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                mainPart.Document.Body.Append(altChunk);
                wordDocument.Save();
                wordDocument.Close();
            }
        }
Example #13
0
        public static void ValidateWordDocument(string filepath)
        {
            using (WordprocessingDocument wordprocessingDocument =
                       WordprocessingDocument.Open(filepath, true))
            {
                try
                {
                    OpenXmlValidator validator = new OpenXmlValidator();
                    int count = 0;
                    foreach (ValidationErrorInfo error in
                             validator.Validate(wordprocessingDocument))
                    {
                        count++;
                        Console.WriteLine("Error " + count);
                        Console.WriteLine("Description: " + error.Description);
                        Console.WriteLine("ErrorType: " + error.ErrorType);
                        Console.WriteLine("Node: " + error.Node);
                        Console.WriteLine("Path: " + error.Path.XPath);
                        Console.WriteLine("Part: " + error.Part.Uri);
                        Console.WriteLine("-------------------------------------------");
                    }

                    Console.WriteLine("count={0}", count);
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                wordprocessingDocument.Close();
            }
        }
Example #14
0
        internal void SaveChanges()
        {
            if (MainDocumentPart == null)
            {
                return;
            }

            // Serialize the XDocument object back to the package.
            using (var xw = XmlWriter.Create(_wordDocument.MainDocumentPart.GetStream(FileMode.Create, FileAccess.Write)))
            {
                MainDocumentPart.Save(xw);
            }

            if (NumberingPart != null)
            {
                // Serialize the XDocument object back to the package.
                using (var xw = XmlWriter.Create(_wordDocument.MainDocumentPart.NumberingDefinitionsPart.GetStream(FileMode.Create,
                                                                                                                   FileAccess.Write)))
                {
                    NumberingPart.Save(xw);
                }
            }

            foreach (var footer in FooterParts)
            {
                footer.Save();
            }
            foreach (var header in HeaderParts)
            {
                header.Save();
            }

            _wordDocument.Close();
        }
Example #15
0
        public IActionResult DownloadFile(VizhenerViewModel model)
        {
            try
            {
                MemoryStream           mem          = new MemoryStream();
                WordprocessingDocument wordDocument = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true);

                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                mainPart.Document = new Document();
                Body      body = mainPart.Document.AppendChild(new Body());
                Paragraph para = body.AppendChild(new Paragraph());
                Run       run  = para.AppendChild(new Run());
                run.AppendChild(new Text(model.Result));
                mainPart.Document.Save();
                wordDocument.Close();
                mem.Position = 0;

                return(File(mem, "application/docx", "result.docx"));
            }
            catch (Exception)
            {
                model.Error = "Ошибка при создании файла";
                return(View("Index", model));
            }
        }
Example #16
0
        // To search and replace content in a document part.
        public void SearchAndReplace(string document, Dictionary <string, string> myDictionary)
        {
            string docText;

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
            {
                docText = null;
                using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }

                foreach (KeyValuePair <string, string> entry in myDictionary)
                {
                    Regex regexText  = new Regex(entry.Key);
                    var   paramValue = entry.Value;
                    docText = regexText.Replace(docText, paramValue);
                }

                using (StreamWriter sw = new StreamWriter(
                           wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
                {
                    sw.Write(docText);
                }
                wordDoc.Close();
            }
        }
Example #17
0
        // ************************************************
        // Main
        // ************************************************
        static void Main(string[] args)
        {
            string theFile              = @"C:\temp\sample.docx";
            WordprocessingDocument doc  = WordprocessingDocument.Open(theFile, false);
            string       body_table     = "DocumentFormat.OpenXml.Wordprocessing.Table";
            string       body_paragraph = "DocumentFormat.OpenXml.Wordprocessing.Paragraph";
            Body         body           = doc.MainDocumentPart.Document.Body;
            StreamWriter sw1            = new StreamWriter("paragraphs.log");

            foreach (var b in body)
            {
                string body_type = b.ToString();
                if (body_type == body_paragraph)
                {
                    string str = getWordStyleValue(b.InnerXml);
                    if (str == "" || str == "HeadingNon-TOC" || str == "TOC1" || str == "TOC2" || str == "TableofFigures" || str == "AcronymList")
                    {
                        continue;
                    }
                    sw1.WriteLine(str + "," + b.InnerText);
                }
                if (body_type == body_table)
                {
                    //       sw1.WriteLine("Table:\n{0}",b.InnerText);
                }
            }
            doc.Close();
            sw1.Close();
        }
        protected void ReplaceCustomXML()
        {
            //Copy từ file gốc ra 1 bản
            string _pathOrigin = Server.MapPath("/File/Template/TemplateHDDV.docx");
            string _pathNew    = Server.MapPath("/File/WordFile/W001.docx");

            if (File.Exists(_pathNew))
            {
                File.Delete(_pathNew);
            }
            if (File.Exists(_pathOrigin))
            {
                File.Copy(_pathOrigin, _pathNew);

                var docText = "";
                WordprocessingDocument docR      = WordprocessingDocument.Open(_pathNew, true);
                MainDocumentPart       mainPartR = docR.MainDocumentPart;
                using (StreamReader sr = new StreamReader(docR.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                    docText = docText.Replace("MerPos01", "001");
                    docText = docText.Replace("MerPos02", "002");
                    docText = docText.Replace("MerPos03", "003");
                    docText = docText.Replace("MerPos04", "004");
                    docText = docText.Replace("MerPos05", "005");
                }
                using (StreamWriter sw = new StreamWriter(docR.MainDocumentPart.GetStream(FileMode.Create)))
                {
                    sw.Write(docText);
                }

                docR.Close();
            }
        }
Example #19
0
        /// <summary>
        /// Validates and returns errors of document.
        /// </summary>
        /// <param name="filepath">The document path.</param>
        /// <param name="errors">The document errors.</param>
        /// <returns>Returns true if document has no errors</returns>
        public static bool ValidateWordDocument(string filepath, out List <string> errors)
        {
            errors = new List <string>();

            using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true))
            {
                try
                {
                    OpenXmlValidator validator = new OpenXmlValidator();

                    foreach (ValidationErrorInfo error in validator.Validate(wordprocessingDocument))
                    {
                        errors.Add($"Error: {errors.Count} Description: {error.Description} ErrorType: {error.ErrorType} Node: {error.Node} Path: {error.Path.XPath} Part: { error.Part.Uri} ");
                    }
                }
                catch (Exception ex)
                {
                    errors.Add(ex.Message);
                }

                wordprocessingDocument.Close();
            }

            return(errors.Count <= 0);
        }
Example #20
0
        public static void MakeDocxFile(string Encrypted, string fileName)
        {
            try
            {
                Regex regexDocx = new Regex(@"[^/*<>|+%!@]+.docx$");//сделанно только для тестов
                if (!regexDocx.IsMatch(fileName))
                {
                    throw new Exception();
                }

                List <string> stringi = Encrypted.Split('\n').ToList <string>();
                using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Create(fileName, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
                {
                    MainDocumentPart mainPart = wordprocessingDocument.AddMainDocumentPart();
                    mainPart.Document = new Document();
                    // Вы реально читаете код??
                    Body body = mainPart.Document.AppendChild(new Body());
                    // Add new text.
                    foreach (var item in stringi)
                    {
                        Paragraph para = body.AppendChild(new Paragraph());
                        Run       run  = para.AppendChild(new Run());
                        run.AppendChild(new Text(item));
                    }
                    // Close the handle explicitly.
                    wordprocessingDocument.Close();
                }
            }
            catch (Exception x) { }
        }
Example #21
0
        /// <summary>
        /// Write html
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="folderName"></param>
        /// <returns></returns>
        private string WriteHtml(string fileName, string folderName)
        {
            imageDirectory = folderName;
            string htmlBody = "";

            try
            {
                document = WordprocessingDocument.Open(fileName, false);

                foreach (OpenXmlElement element in document.MainDocumentPart.Document.Body.Elements <OpenXmlElement>())
                {
                    if (element is Paragraph)
                    {
                        htmlBody += AddParagraph((Paragraph)element);
                    }
                    else if (element is Table)
                    {
                        htmlBody += AddTable((Table)element);
                    }
                }

                document.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(GetHtml(htmlBody));
        }
Example #22
0
        /* 模板格式提取 */
        private void getTemplateStyle(string templatePath, List <Module> modList)
        {
            string templateName   = Path.GetFileNameWithoutExtension(templatePath);// 没有扩展名的文件名
            string templateFolder = "Templates\\" + templateName;

            try
            {
                if (!Directory.Exists(templateFolder))
                {
                    Console.WriteLine("论文模板格式提取开始!");
                    Directory.CreateDirectory(templateFolder);
                    WordprocessingDocument wd = WordprocessingDocument.Open(templatePath, true);
                    getModulesStyle(wd, templateFolder, modList);
                    wd.Close();
                }
                else
                {
                    Console.WriteLine("论文模板已存在,不再提取格式!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("论文模板文件夹创建失败: ", e.ToString());
            }
        }
Example #23
0
        protected void Validate(string path)
        {
            using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(path, false))
            {
                try
                {
                    OpenXmlValidator validator = new OpenXmlValidator(DocumentFormat.OpenXml.FileFormatVersions.Office2010);
                    var validation             = validator.Validate(wordprocessingDocument);

                    var sb = new StringBuilder();

                    foreach (ValidationErrorInfo error in validation)
                    {
                        sb.AppendLine("Description: " + error.Description);
                        sb.AppendLine("ErrorType: " + error.ErrorType);
                        sb.AppendLine("Node: " + error.Node);
                        sb.AppendLine("Path: " + error.Path.XPath);
                        sb.AppendLine("Part: " + error.Part.Uri);

                        sb.AppendLine(string.Empty);
                    }

                    if (validation.Count() > 0)
                    {
                        Assert.Fail(sb.ToString());
                    }
                }
                finally
                {
                    wordprocessingDocument.Close();
                }
            }
        }
Example #24
0
        // Create a Word document using the OpenXML library
        internal Stream CreateCustomerDirectoryDocument(List <Customer> customers)
        {
            MemoryStream result = new MemoryStream();

            using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(result, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());

                foreach (var customer in customers)
                {
                    Paragraph para = body.AppendChild(new Paragraph());
                    Run       run  = para.AppendChild(new Run());

                    run.AppendChild(new Text(customer.name));
                    run.AppendChild(new CarriageReturn());
                    run.AppendChild(new Text(customer.street));
                    run.AppendChild(new CarriageReturn());
                    run.AppendChild(new Text(string.Format("{0} {1}", customer.zipCode, customer.city)));
                    run.AppendChild(new CarriageReturn());
                }

                wordDocument.Close();
            }

            result.Position = 0;
            return(result);
        }
        public async Task ReplaceInternalImage(MemoryStream memoryStream, string oldImagesPlaceholderText, string image)
        {
            if (image != null)
            {
                string[] splitStringImage = image.Split(",");

                var newImageBytes = Convert.FromBase64String(splitStringImage[1]);

                using (WordprocessingDocument document = WordprocessingDocument.Open(memoryStream, true))
                {
                    IEnumerable <Drawing> drawings = document.MainDocumentPart.Document.Descendants <Drawing>().ToList();
                    foreach (Drawing drawing in drawings)
                    {
                        DocProperties dpr = drawing.Descendants <DocProperties>().FirstOrDefault();
                        if (dpr != null && dpr.Name == oldImagesPlaceholderText)
                        {
                            foreach (A.Blip b in drawing.Descendants <A.Blip>().ToList())
                            {
                                OpenXmlPart imagePart = document.MainDocumentPart.GetPartById(b.Embed);

                                if (newImageBytes != null)
                                {
                                    using (var writer = new BinaryWriter(imagePart.GetStream()))
                                    {
                                        writer.Write(newImageBytes);
                                    }
                                }
                            }
                        }
                    }
                    document.Close();
                }
            }
        }
        /// <summary>
        /// Update the OTC codes for the current entity type name
        /// </summary>
        /// <param name="documentContent"></param>
        /// <param name="sourceETN"></param>
        /// <param name="sourceOTC"></param>
        /// <param name="targetOTC"></param>
        /// <returns></returns>
        private void UpdateOTCCodes()
        {
            using (var ms = new MemoryStream(this.FileContents)) {
                // create a word doc from stream
                WordprocessingDocument wordDoc = WordprocessingDocument.Open(ms, true);

                // instantiate the parts of the word doc
                OpenXmlPart mainDocPart = wordDoc.MainDocumentPart;
                IEnumerable <OpenXmlPart> docHeaderParts = mainDocPart.Parts.Where(p => p.OpenXmlPart is HeaderPart).Select(p => p.OpenXmlPart);
                IEnumerable <OpenXmlPart> docFooterParts = mainDocPart.Parts.Where(p => p.OpenXmlPart is FooterPart).Select(p => p.OpenXmlPart);
                IEnumerable <OpenXmlPart> customParts    = mainDocPart.Parts.Where(p => p.OpenXmlPart is CustomXmlPart).Select(p => p.OpenXmlPart);

                IEnumerable <OpenXmlPart> customPropParts =
                    from parent in customParts
                    from child in parent.Parts
                    where child.OpenXmlPart is CustomXmlPropertiesPart
                    select child.OpenXmlPart;

                // change type codes in each part
                UpdateDocumentPart(mainDocPart, EntityTypeName, ObjectTypeCode, TargetOTC);

                UpdateDocumentParts(docHeaderParts, EntityTypeName, ObjectTypeCode, TargetOTC);
                UpdateDocumentParts(docFooterParts, EntityTypeName, ObjectTypeCode, TargetOTC);
                UpdateDocumentParts(customParts, EntityTypeName, ObjectTypeCode, TargetOTC);
                UpdateDocumentParts(customPropParts, EntityTypeName, ObjectTypeCode, TargetOTC);

                // get wordDoc back into format required for CRM
                wordDoc.Close();

                this.FileContents = ms.ToArray();
            };
        }
Example #27
0
    public static void ValidateWordDocument(string filepath)
    {
        filepath = Path.GetFullPath(filepath);
        Console.WriteLine("Validating {0} ...", filepath);
        try {
            WordprocessingDocument doc       = WordprocessingDocument.Open(filepath, false);
            OpenXmlValidator       validator = new OpenXmlValidator();
            int count = 0;
            foreach (ValidationErrorInfo error in validator.Validate(doc))
            {
                count++;
                Console.WriteLine("Error " + count);
                Console.WriteLine("Description: " + error.Description);
                Console.WriteLine("ErrorType: " + error.ErrorType);
                Console.WriteLine("Node: " + error.Node);
                Console.WriteLine("Path: " + error.Path.XPath);
                Console.WriteLine("Part: " + error.Part.Uri);
                Console.WriteLine("-------------------------------------------");
            }

            Console.WriteLine("count={0}", count);

            doc.Close();
        } catch (Exception e) {
            Console.WriteLine(e);
        }
    }
Example #28
0
        static void FillTemplate(Stream stream, XmlDocument data)
        {
            WordprocessingDocument
                wordprocessingDocument = WordprocessingDocument.Open(stream, true);

            var
                bookmarksCollection = wordprocessingDocument.MainDocumentPart.RootElement.Descendants <BookmarkStart>();

            foreach (XmlNode node in data.DocumentElement.ChildNodes)
            {
                string
                             nodeName = node.Name;

                BookmarkStart
                    bookmarkStart;

                if ((bookmarkStart = bookmarksCollection.Where(b => b.Name == nodeName).Select(b => b).FirstOrDefault()) != null)
                {
                    if (node.ChildNodes.Count == 1)
                    {
                        Fill(node, bookmarkStart);
                    }
                    else
                    {
                        Fill(node, GetTable(bookmarkStart));
                    }
                }
            }

            wordprocessingDocument.Close();
        }
Example #29
0
        public static void ExportCaseToDoc(Case caseFile, string mapImagePath, string folderName)
        {
            using (WordprocessingDocument wordprocessingDocument =
                       WordprocessingDocument.Create(Path.Combine(folderName, string.Format("CaseReport-{0}.docx", caseFile.CaseNumber)), WordprocessingDocumentType.Document))
            {
                //wordprocessingDocument.AddMainDocumentPart();

                MainDocumentPart mainPart = wordprocessingDocument.AddMainDocumentPart();
                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());
                var  para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
                var  run  = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());

                run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text(string.Format("GPS Coordinate Report: Case #{0}", caseFile.CaseNumber)));
                ApplyStyleToParagraph(wordprocessingDocument, "Title", "Title", para);
                AddTable(body, caseFile.GPSCoordinates.Where(g => g.IncludedInMap).OrderBy(g => g.FileTime).ToList());
                using (FileStream fs = new FileStream(mapImagePath, FileMode.Open, FileAccess.Read))
                {
                    ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);
                    imagePart.FeedData(fs);
                    AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
                }

                //wordprocessingDocument.Save();
                wordprocessingDocument.Close();
            }
        }
Example #30
0
        public static void EditFile(string inputFilePath, string outputFilePath)
        {
            if (LoadFile(inputFilePath, outputFilePath))
            {
                wpDoc = WordprocessingDocument.Open(outputFilePath, true);

                body = wpDoc.MainDocumentPart.Document.Body;

                tab = body.Elements <Table>().ElementAt(1);

                rProp = SetFormatting("Arial", 18);

                FillCells();
                FormatCells();
                MergeCellsInColumn(0);
                // MergeCells();

                try
                {
                    wpDoc.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
Example #31
0
        // Close a document
        public static bool closeDocument(WordprocessingDocument doc)
        {
            try
            {
                doc.Close();
                return true;
            }
            catch (Exception)
            {

                return false;
            }
        }
Example #32
0
        /// <summary>
        /// Write html
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="folderName"></param>
        /// <returns></returns>
        private string WriteHtml(string fileName, string folderName)
        {
            imageDirectory = folderName;
            string htmlBody = "";

            try
            {
                document = WordprocessingDocument.Open(fileName, false);

                foreach (OpenXmlElement element in document.MainDocumentPart.Document.Body.Elements<OpenXmlElement>())
                    if (element is Paragraph)
                        htmlBody += AddParagraph((Paragraph)element);
                    else if (element is Table)
                        htmlBody += AddTable((Table)element);

                document.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return GetHtml(htmlBody);
        }
Example #33
0
 public void TableToWord(Wordprocessing.Table table, WordprocessingDocument document)
 {
     Wordprocessing.Body body = new Wordprocessing.Body();
     Wordprocessing.Paragraph paragraph = new Wordprocessing.Paragraph();
     body.Append(table);
     body.Append(paragraph);
     document.MainDocumentPart.Document.AppendChild(body);
     document.MainDocumentPart.Document.Save();
     document.Close();
 }