Пример #1
0
        public static void AddStyleToDoc(MainDocumentPart mainPart, string styleid, string stylename, StyleRunProperties styleRunProperties)
        {
            // Get the Styles part for this document.
            StyleDefinitionsPart part =
                mainPart.StyleDefinitionsPart;

            // If the Styles part does not exist, add it and then add the style.
            if (part == null)
            {
                part = AddStylesPartToPackage(mainPart);
                AddNewStyle(part, styleid, stylename, styleRunProperties);
            }
            else
            {
                //// If the style is not in the document, add it.
                //if (IsStyleIdInDocument(mainPart, styleid) != true)
                //{
                //    // No match on styleid, so let's try style name.
                //    string styleidFromName = GetStyleIdFromStyleName(mainPart, stylename);
                //    if (styleidFromName == null)
                //    {
                //        AddNewStyle(part, styleid, stylename, styleRunProperties);
                //    }
                //    else
                //        styleid = styleidFromName;
                //}
            }
        }
Пример #2
0
        // Return true if the style id is in the document, false otherwise.
        public static bool IsStyleIdInDocument(StyleDefinitionsPart part,
                                               string styleid)
        {
            // Get access to the Styles element for this document.
            Styles s = part.Styles;

            // Check that there are styles and how many.
            int n = s.Elements <Style>().Count();

            if (n == 0)
            {
                return(false);
            }

            // Look for a match on styleid.
            Style style = s.Elements <Style>()
                          .Where(st => (st.StyleId == styleid) && (st.Type == StyleValues.Paragraph))
                          .FirstOrDefault();

            if (style == null)
            {
                return(false);
            }

            return(true);
        }
Пример #3
0
        // // // // //
        // 6th test //
        // // // // //
        public static void CreateFileAndAddDocumentDefaultStyles() // create new OpenXML doc with document default styles
        {
            string outputFileNameAndPath = Path.Combine(Program.outputFilePath, Guid.NewGuid().ToString() + "_file_with_added_doc_default_styles" + ".docx");

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

                mainPart.Document = new Document();


                StyleDefinitionsPart stylePart = mainPart.StyleDefinitionsPart; // get the Styles part for this document
                stylePart = AddStylesPartToPackage(mainPart);

                Style style = new Style();
                style.Append(GenerateDocDefaults());

                stylePart.Styles = new Styles(); // add style to the StylePart
                stylePart.Styles.Append(style);
                stylePart.Styles.Save();

                Body body = new Body();
                mainPart.Document.Append(body);
            }

            Console.WriteLine(string.Format("{0}:{1}{2}{1}{3}", "6. File with document default styles added", Environment.NewLine, outputFileNameAndPath, new string('-', 80)));
        }
Пример #4
0
 /// <summary>
 /// Sets a new styles part inside the document
 /// </summary>
 /// <param name="newStylesDocument">Path of styles definition file</param>
 public void SetStylePart(XDocument newStylesDocument)
 {
     try
     {
         // Replaces XDocument with the style file to transfer
         XDocument stylesDocument = GetStylesDocument();
         if (stylesDocument == null)
         {
             StyleDefinitionsPart stylesPart =
                 parentDocument.Document.MainDocumentPart.AddNewPart <StyleDefinitionsPart>();
             stylesDocument = parentDocument.GetXDocument(stylesPart);
         }
         if (stylesDocument.Root == null)
         {
             stylesDocument.Add(newStylesDocument.Root);
         }
         else
         {
             stylesDocument.Root.ReplaceWith(newStylesDocument.Root);
         }
     }
     catch (XmlException ex) {
         throw new Exception("File specified is not a valid XML file", ex);
     }
 }
Пример #5
0
        // Create a new style with the specified styleid and stylename and add it to the specified
        // style definitions part.
        private static void AddNewStyle(StyleDefinitionsPart styleDefinitionsPart,
                                        string styleid, string stylename)
        {
            // Get access to the root element of the styles part.
            Styles styles = styleDefinitionsPart.Styles;

            // Create a new paragraph style and specify some of the properties.
            Style style = new Style()
            {
                Type        = StyleValues.Paragraph,
                StyleId     = styleid,
                CustomStyle = true
            };
            StyleName styleName1 = new StyleName()
            {
                Val = stylename
            };
            BasedOn basedOn1 = new BasedOn()
            {
                Val = "Normal"
            };
            NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle()
            {
                Val = "Normal"
            };

            style.Append(styleName1);
            style.Append(basedOn1);
            style.Append(nextParagraphStyle1);

            // Create the StyleRunProperties object and specify some of the run properties.
            StyleRunProperties styleRunProperties1 = new StyleRunProperties();
            Bold  bold1  = new Bold();
            Color color1 = new Color()
            {
                ThemeColor = ThemeColorValues.Accent2
            };
            RunFonts font1 = new RunFonts()
            {
                Ascii = "Lucida Console"
            };
            Italic italic1 = new Italic();
            // Specify a 12 point size.
            FontSize fontSize1 = new FontSize()
            {
                Val = "24"
            };

            styleRunProperties1.Append(bold1);
            styleRunProperties1.Append(color1);
            styleRunProperties1.Append(font1);
            styleRunProperties1.Append(fontSize1);
            styleRunProperties1.Append(italic1);

            // Add the run properties to the style.
            style.Append(styleRunProperties1);

            // Add the style to the styles part.
            styles.Append(style);
        }
Пример #6
0
        public static byte[] HtmlToWordMethod11(String html)
        {
            const string filename = "test.docx";

            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            using (MemoryStream generatedDocument = new MemoryStream())
            {
                using (WordprocessingDocument package = WordprocessingDocument.Create(
                           generatedDocument, WordprocessingDocumentType.Document))
                {
                    MainDocumentPart mainPart = package.MainDocumentPart;
                    if (mainPart == null)
                    {
                        mainPart = package.AddMainDocumentPart();
                        new Document(new Body()).Save(mainPart);
                    }
                    HtmlConverter converter = new HtmlConverter(mainPart);
                    var           sections  = mainPart.Document.Descendants <SectionProperties>();

                    Body body = mainPart.Document.Body;
                    SectionProperties sectProp = new SectionProperties();
                    PageSize          pageSize = new PageSize()
                    {
                        Width = 15840U, Height = 12240U, Orient = PageOrientationValues.Landscape
                    };
                    PageMargin pageMargin = new PageMargin()
                    {
                        Top = 1440, Right = 1440U, Bottom = 1440, Left = 1440U
                    };
                    Columns columns = new Columns()
                    {
                        Space = "720"
                    };
                    DocGrid docGrid = new DocGrid()
                    {
                        LinePitch = 360
                    };
                    sectProp.Append(pageSize, pageMargin, columns, docGrid);
                    body.Append(sectProp);
                    var paragraphs = converter.Parse(html);
                    for (int i = 0; i < paragraphs.Count; i++)
                    {
                        body.Append(paragraphs[i]);
                    }
                    foreach (TableRow t in body.Descendants <TableRow>())
                    {
                        t.Append(new CantSplit());
                    }
                    StyleDefinitionsPart stylesPart = null;
                    stylesPart = mainPart.StyleDefinitionsPart;
                    ChangeStyleDefinitionsPart1(stylesPart);
                    mainPart.Document.Save();
                }
                return(generatedDocument.ToArray());
            }
        }
Пример #7
0
        private void GenerateStyleDefinitions(StyleDefinitionsPart definitionsPart)
        {
            definitionsPart.Styles = new Styles();

            var style = new Style()
            {
                Type    = StyleValues.Paragraph,
                StyleId = "ListParagraph"
            };

            var styleParagraphProperties = new StyleParagraphProperties(
                new Indentation()
            {
                Left = "720"
            },
                new ContextualSpacing());


            style.AppendChild(new StyleName()
            {
                Val = "List Paragraph"
            });
            style.AppendChild(styleParagraphProperties);

            styleDefinitionsPart.Styles.AppendChild(style);
        }
Пример #8
0
        public void addHeading1Style(MainDocumentPart mainPart)
        {
            // we have to set the properties
            RunProperties rPr   = new RunProperties();
            Color         color = new Color()
            {
                Val = "FF0000"
            };                                            // the color is red
            RunFonts rFont = new RunFonts();

            rFont.Ascii = "Arial"; // the font is Arial
            rPr.Append(color);
            rPr.Append(rFont);
            rPr.Append(new Bold()); // it is Bold
            rPr.Append(new FontSize()
            {
                Val = "28"
            });                                        //font size (in 1/72 of an inch)

            Style style = new Style();

            style.StyleId = "MyHeading1"; //this is the ID of the style
            style.Append(new Name()
            {
                Val = "My Heading 1"
            });                //this is the name of the new style
            style.Append(rPr); //we are adding properties previously defined

            // we have to add style that we have created to the StylePart
            StyleDefinitionsPart stylePart = mainPart.AddNewPart <StyleDefinitionsPart>();

            stylePart.Styles = new Styles();
            stylePart.Styles.Append(style);
            stylePart.Styles.Save(); // we save the style part
        }
Пример #9
0
        // Add a StylesDefinitionsPart to the document.  Returns a reference to it.
        public static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument doc)
        {
            StyleDefinitionsPart part = doc.MainDocumentPart.AddNewPart <StyleDefinitionsPart>();
            Styles root = new Styles();

            root.Save(part);
            return(part);
        }
Пример #10
0
        public static void CreateAndAddCharacterStyle(WordprocessingDocument doc, string styleId, string styleName, string aliases, string linkedStyle, IEnumerable <OpenXmlElement> wordStyles)
        {
            // Get the Styles part for this document.
            StyleDefinitionsPart part =
                doc.MainDocumentPart.StyleDefinitionsPart;

            // If the Styles part does not exist, add it.
            if (part == null)
            {
                part = AddStylesPartToPackage(doc);
            }

            // Get access to the root element of the styles part.
            Styles styles = part.Styles;

            // Create a new character style and specify some of the attributes.
            Style style = new Style()
            {
                Type        = StyleValues.Character,
                StyleId     = styleId,
                CustomStyle = true
            };

            // Create and add the child elements (properties of the style).
            Aliases aliases1 = new Aliases()
            {
                Val = aliases
            };
            StyleName styleName1 = new StyleName()
            {
                Val = styleName
            };
            LinkedStyle linkedStyle1 = new LinkedStyle()
            {
                Val = linkedStyle
            };

            if (aliases != "")
            {
                style.Append(aliases1);
            }
            style.Append(styleName1);
            style.Append(linkedStyle1);

            // Create the StyleRunProperties object and specify some of the run properties.
            StyleRunProperties styleRunProperties1 = new StyleRunProperties();

            foreach (var wordStyle in wordStyles)
            {
                styleRunProperties1.Append(wordStyle);
            }

            // Add the run properties to the style.
            style.Append(styleRunProperties1);

            // Add the style to the styles part.
            styles.Append(style);
        }
Пример #11
0
        public static Styles CreateStyles(MainDocumentPart mainPart)
        {
            StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart <StyleDefinitionsPart>();
            Styles styles = new Styles();

            styleDefinitionsPart.Styles = styles;
            //styles.Save();
            return(styles);
        }
Пример #12
0
        // Return styleid that matches the styleName, or null when there's no match.
        public static string GetStyleIdFromStyleName(StyleDefinitionsPart stylePart, string styleName)
        {
            string styleId = stylePart.Styles.Descendants <StyleName>()
                             .Where(s => s.Val.Value.Equals(styleName, StringComparison.InvariantCultureIgnoreCase))
                             //&& (((Style)s.Parent).Type == StyleValues.Paragraph))
                             .Select(n => ((Style)n.Parent).StyleId).First();

            return(styleId);
        }
        private static string GetStyleIdFromStyleName(MainDocumentPart mainPart, string styleName)
        {
            StyleDefinitionsPart stylePart = mainPart.StyleDefinitionsPart;
            string styleId = stylePart.Styles.Descendants <StyleName>()
                             .Where(s => s.Val.Value.Equals(styleName))
                             .Select(n => ((Style)n.Parent).StyleId).FirstOrDefault();

            return(styleId ?? styleName);
        }
        //.....................................................................
        /// <summary>
        /// Apply a style to a paragraph.
        /// </summary>
        /// <param name="worddoc"></param>
        /// <param name="styleid"></param>
        /// <param name="stylename"></param>
        /// <param name="docpara"></param>
        public void ApplyStyleToParagraph(WordprocessingDocument worddoc, string styleid, string stylename, Paragraph docpara)
        {
            // If the paragraph has no ParagraphProperties object, create one.
            if (docpara.Elements <ParagraphProperties>( ).Count( ) == 0)
            {
                docpara.PrependChild <ParagraphProperties>(new ParagraphProperties( ));

                //Console.WriteLine( "docpara.Elements<ParagraphProperties>( ).Count( ) == 0" );
            }

            // Get the paragraph properties element of the paragraph.
            ParagraphProperties docparapros = docpara.Elements <ParagraphProperties>( ).First( );

            // Get the Styles wbookpart for this docxname.
            StyleDefinitionsPart part = worddoc.MainDocumentPart.StyleDefinitionsPart;

            // If the Styles wbookpart does not exist, add it and then add the style.
            if (part == null)
            {
                Console.WriteLine("if ( part == null )");

                part = this.AddStylesPartToPackage(worddoc);

                this.AddNewStyle(part, styleid, stylename);
            }
            else
            {
                Console.WriteLine("if ( part == null ) else else else else else else");

                // If the style is not in the docxname, add it.
                if (IsStyleIdInDocument(worddoc, styleid) != true)
                {
                    Console.WriteLine("if ( IsStyleIdInDocument( worddoc, styleid ) != true )");

                    // No match on styleid, so let's try style name.
                    string styleidFromName = GetStyleIdFromStyleName(worddoc, stylename);

                    if (styleidFromName == null)
                    {
                        AddNewStyle(part, styleid, stylename);
                    }
                    else
                    {
                        styleid = styleidFromName;
                    }
                }
            }

            // Set the style of the paragraph.
            docparapros.ParagraphStyleId = new ParagraphStyleId( )
            {
                Val = styleid
            };

            return;
        }
Пример #15
0
        static void Main(string[] args)
        {
            string FilePath = @"..\..\..\..\Sample Files\";
            string File     = FilePath + "Create and add a paragraph style - OpenXML.docx";

            using (WordprocessingDocument doc =
                       WordprocessingDocument.Open(File, true))
            {
                // Get the Styles part for this document.
                StyleDefinitionsPart part =
                    doc.MainDocumentPart.StyleDefinitionsPart;

                // If the Styles part does not exist, add it and then add the style.
                if (part == null)
                {
                    part = AddStylesPartToPackage(doc);
                }

                // Set up a variable to hold the style ID.
                string parastyleid = "OverdueAmountPara";

                // Create and add a paragraph style to the specified styles part
                // with the specified style ID, style name and aliases.
                CreateAndAddParagraphStyle(part,
                                           parastyleid,
                                           "Overdue Amount Para",
                                           "Late Due, Late Amount");

                // Add a paragraph with a run and some text.
                Paragraph p =
                    new Paragraph(
                        new Run(
                            new Text("This is some text in a run in a paragraph.")));

                // Add the paragraph as a child element of the w:body element.
                doc.MainDocumentPart.Document.Body.AppendChild(p);

                // If the paragraph has no ParagraphProperties object, create one.
                if (p.Elements <ParagraphProperties>().Count() == 0)
                {
                    p.PrependChild <ParagraphProperties>(new ParagraphProperties());
                }

                // Get a reference to the ParagraphProperties object.
                ParagraphProperties pPr = p.ParagraphProperties;

                // If a ParagraphStyleId object doesn't exist, create one.
                if (pPr.ParagraphStyleId == null)
                {
                    pPr.ParagraphStyleId = new ParagraphStyleId();
                }

                // Set the style of the paragraph.
                pPr.ParagraphStyleId.Val = parastyleid;
            }
        }
Пример #16
0
        // Return styleid that matches the styleName, or null when there's no match.
        public static string GetStyleIdFromStyleName(WordprocessingDocument doc, string styleName)
        {
            StyleDefinitionsPart stylePart = doc.MainDocumentPart.StyleDefinitionsPart;
            string styleId = stylePart.Styles.Descendants <StyleName>()
                             .Where(s => s.Val.Value.Equals(styleName) &&
                                    (((Style)s.Parent).Type == StyleValues.Paragraph))
                             .Select(n => ((Style)n.Parent).StyleId).FirstOrDefault();

            return(styleId);
        }
Пример #17
0
        private static void AddNewStyle(StyleDefinitionsPart styleDefinitionsPart, string styleid, string stylename)
        {
            Styles styles = styleDefinitionsPart.Styles;
            //创建一个新的段落style 并且配置一些新属性
            Style style = new Style()
            {
                Type        = StyleValues.Paragraph,
                StyleId     = styleid,
                CustomStyle = true
            };
            StyleName styleName1 = new StyleName()
            {
                Val = stylename
            };
            BasedOn basedOn1 = new BasedOn()
            {
                Val = "Normal"
            };
            NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle()
            {
                Val = "Normal"
            };

            style.Append(styleName1);
            style.Append(basedOn1);
            style.Append(nextParagraphStyle1);

            //字体
            StyleRunProperties styleRunProperties1 = new StyleRunProperties();
            Bold  bold1  = new Bold();
            Color color1 = new Color()
            {
                ThemeColor = ThemeColorValues.Accent2
            };
            RunFonts font1 = new RunFonts()
            {
                Ascii = "Lucida Console", EastAsia = "宋体"
            };
            Italic italic1 = new Italic();
            //字体大小
            FontSize fontSize1 = new FontSize()
            {
                Val = "24"
            };

            styleRunProperties1.Append(bold1);
            styleRunProperties1.Append(color1);
            styleRunProperties1.Append(font1);
            styleRunProperties1.Append(fontSize1);
            styleRunProperties1.Append(italic1);

            style.Append(styleRunProperties1);
            styles.Append(style);
        }
        /// <summary>
        /// Adds a style definition part if it doesn't exist.
        /// </summary>
        /// <param name="mainPart">The document main part</param>
        /// <remarks>
        /// In this context (document creation), the style does not exist.
        /// When a document is created programatically, it does not automatically
        /// add a style part such as when creating with MS Word.
        /// </remarks>
        private void AddStylesToMainDocumentPart(MainDocumentPart mainPart)
        {
            StyleDefinitionsPart part = mainPart.StyleDefinitionsPart;

            if (part == null)
            {
                part = mainPart.AddNewPart <StyleDefinitionsPart>();
                Styles root = new Styles();
                root.Save(part);
            }
        }
Пример #19
0
        public static void AddStyle(MainDocumentPart mainPart, string styleId, string styleName,
                                    string fontName, int fontSize, string rgbColor, bool isBold, bool isItalic, bool isUnderLined)
        {
            // we have to set the properties
            RunProperties rPr   = new RunProperties();
            Color         color = new Color()
            {
                Val = rgbColor
            };
            RunFonts rFont = new RunFonts();

            rFont.Ascii = fontName;
            rPr.Append(color);
            rPr.Append(rFont);
            if (isBold)
            {
                rPr.Append(new Bold());
            }
            if (isItalic)
            {
                rPr.Append(new Italic());
            }
            if (isUnderLined)
            {
                rPr.Append(new Underline()
                {
                    Val = UnderlineValues.Single
                });
            }
            rPr.Append(new FontSize()
            {
                Val = (fontSize * 2).ToString()
            });

            Style style = new Style();

            style.StyleId = styleId;
            if (styleName == null || styleName.Length == 0)
            {
                styleName = styleId;
            }
            style.Append(new Name()
            {
                Val = styleName
            });                //this is the name of the new style
            style.Append(rPr); //we are adding properties previously defined

            // we have to add style that we have created to the StylePart
            StyleDefinitionsPart stylePart = mainPart.AddNewPart <StyleDefinitionsPart>();

            stylePart.Styles = new Styles();
            stylePart.Styles.Append(style);
            stylePart.Styles.Save(); // we save the style part
        }
Пример #20
0
        public static void Test_03()
        {
            //Test_OpenXml_Style.SetDirectory();
            string file = "test_01.docx";

            Trace.WriteLine("create docx \"{0}\" using OXmlDoc", file);

            // from How to: Create and add a paragraph style to a word processing document (Open XML SDK) https://msdn.microsoft.com/fr-fr/library/office/gg188062.aspx

            using (WordprocessingDocument doc = WordprocessingDocument.Open(file, true))
            {
                // Get the Styles part for this document.
                StyleDefinitionsPart part = doc.MainDocumentPart.StyleDefinitionsPart;

                // If the Styles part does not exist, add it and then add the style.
                if (part == null)
                {
                    part = AddStylesPartToPackage(doc);
                }

                // Set up a variable to hold the style ID.
                string parastyleid = "OverdueAmountPara";

                // Create and add a paragraph style to the specified styles part
                // with the specified style ID, style name and aliases.
                CreateAndAddParagraphStyle(part, parastyleid, "Overdue Amount Para", "Late Due, Late Amount");

                // Add a paragraph with a run and some text.
                //Paragraph p = new Paragraph(new Run(new Text("This is some text in a run in a paragraph.")));
                Paragraph p = new Paragraph(new Run(new DocumentFormat.OpenXml.Wordprocessing.Text("This is some text in a run in a paragraph.")));

                // Add the paragraph as a child element of the w:body element.
                doc.MainDocumentPart.Document.Body.AppendChild(p);

                // If the paragraph has no ParagraphProperties object, create one.
                if (p.Elements <ParagraphProperties>().Count() == 0)
                {
                    p.PrependChild <ParagraphProperties>(new ParagraphProperties());
                }

                // Get a reference to the ParagraphProperties object.
                ParagraphProperties pPr = p.ParagraphProperties;

                // If a ParagraphStyleId object doesn't exist, create one.
                if (pPr.ParagraphStyleId == null)
                {
                    pPr.ParagraphStyleId = new ParagraphStyleId();
                }

                // Set the style of the paragraph.
                pPr.ParagraphStyleId.Val = parastyleid;
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="WordDocumentReportWriter" /> class.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        public WordDocumentReportWriter(string filePath)
        {
            this.FileName = filePath;
            this.package  = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document);

            this.mainPart = this.package.AddMainDocumentPart();

            this.stylePart = this.mainPart.AddNewPart <StyleDefinitionsPart>();

            // fontTablePart = mainPart.AddNewPart<FontTablePart>();
            this.document = CreateDocument();
            this.body     = new Body();
        }
Пример #22
0
        public void SaveTo(string path)
        {
            using (WordprocessingDocument package = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document))
            {
                package.AddMainDocumentPart();
                package.MainDocumentPart.Document = document;

                StyleDefinitionsPart styleDefinitionsPart1 = package.MainDocumentPart.AddNewPart <StyleDefinitionsPart>("rId1");
                GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1);

                package.MainDocumentPart.Document.Save();
            }
        }
Пример #23
0
        public static void WriteToWordDoc(string filepath)
        {
            // Open a WordprocessingDocument for editing using the filepath.
            using (WordprocessingDocument wordprocessingDocument =
                       WordprocessingDocument.Open(filepath, true))
            {
                // Get a reference to the main document part.
                MainDocumentPart docPart = wordprocessingDocument.MainDocumentPart;
                // Assign a reference to the existing document body.
                Body body = docPart.Document.Body;

                RemoveBorderAndShadingFromFirstMainTitle(body);

                //paragraph dynamically bind after remove node , so this may can call last in function
                RemoveEmptyParagraphBeforeMainTitle(body);

                RemoveEmptyParagraphAfterSecondMainTitle(body);

                //getting all paragraph in document
                IEnumerable <Paragraph> allParagraph = body.Descendants <Paragraph>();

                //adding a new style and later will be implemented in all paragraphs
                StyleDefinitionsPart stylDefPart = docPart.StyleDefinitionsPart;
                Style styl = CreateParagraphCharacterStyle();
                stylDefPart.Styles.AppendChild(styl);

                AddingFontAndFontSizeToAllParagraphExcludingMainAndSecondTitle(allParagraph);

                AddingFontAndFontSizeToSecondaryTitle(body, allParagraph);


                //getting all tables in document
                IEnumerable <Table> allTables = body.Descendants <Table>();

                foreach (var iTable in allTables)
                {
                    AddBorderToTableProperties(iTable);

                    AddStyleToTableHeaderRow(iTable);

                    AddStyleToTableRestOfRows(iTable);
                }//end of foreach all tables

                RemoveHeaderAndFooter(docPart);

                ChangePaperSizeAndMargin(docPart);

                //finally saving the document
                docPart.Document.Save();
            }
        }
Пример #24
0
        // Create a new style with the specified styleid and stylename and add it to the specified
        // style definitions part.
        private static void AddNewStyle(StyleDefinitionsPart styleDefinitionsPart,
                                        string styleid, string stylename, StyleValues type,
                                        Action <StyleRunProperties> prepareRunStyle, Action <StyleParagraphProperties> prepareParagraphStyle,
                                        string basedOn = "Normal")
        {
            // Get access to the root element of the styles part.
            Styles styles = styleDefinitionsPart.Styles;

            // Create a new paragraph style and specify some of the properties.
            Style style = new Style()
            {
                Type        = type,
                StyleId     = styleid,
                CustomStyle = true
            };
            StyleName styleName1 = new StyleName()
            {
                Val = stylename
            };
            BasedOn basedOn1 = new BasedOn()
            {
                Val = basedOn
            };
            NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle()
            {
                Val = "Normal"
            };

            style.Append(styleName1);

            if (!string.IsNullOrEmpty(basedOn))
            {
                style.Append(basedOn1);
            }
            //style.Append(nextParagraphStyle1);

            // Create the StyleRunProperties object and specify some of the run properties.
            StyleRunProperties styleRunProperties = new StyleRunProperties();

            prepareRunStyle(styleRunProperties);
            // Add the run properties to the style.
            style.Append(styleRunProperties);

            StyleParagraphProperties styleParaProperties = new StyleParagraphProperties();

            prepareParagraphStyle(styleParaProperties);
            style.Append(styleParaProperties);

            // Add the style to the styles part.
            styles.Append(style);
        }
Пример #25
0
        // Create a new style with the specified styleid and stylename and add it to the specified
        // style definitions part.
        private static void AddNewStyle(StyleDefinitionsPart styleDefinitionsPart,
                                        string styleid, string stylename)
        {
            // Get access to the root element of the styles part.
            Styles styles = styleDefinitionsPart.Styles;

            // Create a new paragraph style and specify some of the properties.
            Style style = new Style()
            {
                Type        = StyleValues.Paragraph,
                StyleId     = styleid,
                CustomStyle = true
            };
            StyleName styleName1 = new StyleName()
            {
                Val = stylename
            };

            //The styles set below probably should be passed in as a parameter and not hard coded, but
            //I only care about the Titles that are being append, so just leaving it for now.
            BasedOn basedOn1 = new BasedOn()
            {
                Val = "Normal"
            };
            NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle()
            {
                Val = "Normal"
            };

            style.Append(styleName1);
            style.Append(basedOn1);
            style.Append(nextParagraphStyle1);

            // Create the StyleRunProperties object and specify some of the run properties.
            StyleRunProperties styleRunProperties1 = new StyleRunProperties();

            // Specify a 12 point size.
            FontSize fontSize1 = new FontSize()
            {
                Val = "24"
            };

            styleRunProperties1.Append(fontSize1);

            // Add the run properties to the style.
            style.Append(styleRunProperties1);

            // Add the style to the styles part.
            styles.Append(style);
        }
Пример #26
0
        /// <summary>
        /// 从文档获取样式库实例
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        private static StyleDefinitionsPart GetStyleDefinitionsPart(WordprocessingDocument doc)
        {
            // Get the Styles part for this document.
            StyleDefinitionsPart part =
                doc.MainDocumentPart.StyleDefinitionsPart;

            // If the Styles part does not exist, add it and then add the style.
            if (part == null)
            {
                part = doc.MainDocumentPart.AddNewPart <StyleDefinitionsPart>();
                Styles root = new Styles();
                root.Save(part);;
            }
            return(part);
        }
Пример #27
0
        private void PrepareStyleForDocument()
        {
            // Add a StylesDefinitionsPart to the document
            StyleDefinitionsPart part = _document.MainDocumentPart.AddNewPart <StyleDefinitionsPart>();
            Styles root = new Styles();

            root.Save(part);

            // Create new style and add to document
            CreateDocumentHeadingStyle();
            CreateWeekHeadingStyle();
            CreateProjectHeadingStyle();
            CreateTextStyle();
            CreateAuthorStyle();
        }
Пример #28
0
        private void PrepareStyleDefinitionsPart(MainDocumentPart mainPart)
        {
            //Add new style part
            StyleDefinitionsPart stylePart = mainPart.AddNewPart <StyleDefinitionsPart>();

            styleH1           = CreateStyle("0000AA", "MyHeading1", "My Heading 1", "Heading1", "Normal", "Arial", 32, JustificationValues.Center, true, 480);
            styleH2_term      = CreateStyle("000077", "MyHeading2", "My Heading 2", "Heading2", "Normal", "Arial", 28, JustificationValues.Left, true, 480);
            style_description = CreateStyle("000000", "Description", "Description", "Normal", "Description", "Arial", 24, JustificationValues.Left, false, 480);
            // we have to add style that we have created to the StylePart
            stylePart.Styles = new Styles();
            stylePart.Styles.Append(styleH1);
            stylePart.Styles.Append(styleH2_term);
            stylePart.Styles.Append(style_description);
            stylePart.Styles.Save(); // we save the style part
        }
        public void CreateAndAddAParagraphStyleFeature()
        {
            using (WordprocessingDocument doc =
                       WordprocessingDocument.Create(ArtifactsDir + "Create and add a paragraph style - OpenXML.docx",
                                                     WordprocessingDocumentType.Document))
            {
                // Get the Styles part for this document.
                // If the Styles part does not exist: add the styles part, and then add the style.
                StyleDefinitionsPart part =
                    doc.MainDocumentPart.StyleDefinitionsPart ?? AddStylesPartToPackage(doc);

                // Set up a variable to hold the style ID.
                string parastyleId = "OverdueAmountPara";

                // Create and add a paragraph style to the specified styles part
                // with the specified style ID, style name, and aliases.
                AddParagraphStyle(part,
                                  parastyleId,
                                  "Overdue Amount Para",
                                  "Late Due, Late Amount");

                // Add a paragraph with a run and some text.
                Paragraph p =
                    new Paragraph(
                        new Run(
                            new Text("This is some text in a run in a paragraph.")));

                // Add the paragraph as a child element of the w:body element.
                doc.MainDocumentPart.Document.Body.AppendChild(p);

                // If the paragraph has no ParagraphProperties object, then create one.
                if (!p.Elements <ParagraphProperties>().Any())
                {
                    p.PrependChild(new ParagraphProperties());
                }

                // Get a reference to the ParagraphProperties object.
                ParagraphProperties pPr = p.ParagraphProperties;

                // If a ParagraphStyleId object doesn't exist, then create one.
                if (pPr.ParagraphStyleId == null)
                {
                    pPr.ParagraphStyleId = new ParagraphStyleId();
                }

                pPr.ParagraphStyleId.Val = parastyleId;
            }
        }
Пример #30
0
        //gavdcodeend 09

        //gavdcodebegin 10
        public static void WordOpenXmlCreateAndApplyStyleParagraph()
        {
            using (WordprocessingDocument myWordDoc =
                       WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true))
            {
                MainDocumentPart     docMainPart = myWordDoc.MainDocumentPart;
                StyleDefinitionsPart stylePart   = docMainPart.StyleDefinitionsPart;

                Style myStyle = new Style
                {
                    Type        = StyleValues.Paragraph,
                    CustomStyle = true,
                    StyleId     = "MyHeading1"
                };

                RunProperties runProps = new RunProperties(
                    new Name()
                {
                    Val = "My Heading 1"
                },
                    new BasedOn()
                {
                    Val = "Heading1"
                },
                    new NextParagraphStyle()
                {
                    Val = "Normal"
                }
                    );

                stylePart.Styles = new Styles();
                stylePart.Styles.Append(myStyle);
                stylePart.Styles.Save();

                Body      docBody      = docMainPart.Document.Body;
                Paragraph docParagraph = docBody.AppendChild(new Paragraph());

                ParagraphProperties paragraphProps = new ParagraphProperties();
                paragraphProps.ParagraphStyleId = new ParagraphStyleId()
                {
                    Val = "MyHeading1"
                };
                docParagraph.Append(paragraphProps);

                Run docRun = docParagraph.AppendChild(new Run());
                docRun.AppendChild(new Text("This is the Heading with style"));
            }
        }