예제 #1
1
        public static void HighlightWord(WordprocessingDocument wordDoc, string word)
        {
            Body body      = wordDoc.MainDocumentPart.Document.Body;
            var  paragraph = body.Descendants <Paragraph>().Where(x => x.InnerText == word);

            foreach (var para in paragraph)
            {
                var subRuns = para.Descendants <Run>().ToList();
                foreach (var run in subRuns)
                {
                    var subRunProp = run.Descendants <RunProperties>().ToList().FirstOrDefault();
                    var newColor   = new Color();
                    newColor.Val = "EF413D";

                    if (subRunProp != null)
                    {
                        var color = subRunProp.Descendants <Color>().FirstOrDefault();
                        subRunProp.ReplaceChild(newColor, color);
                    }
                    else
                    {
                        var tmpSubRunProp = new RunProperties();
                        tmpSubRunProp.AppendChild(newColor);
                        run.AppendChild(tmpSubRunProp);
                    }
                }
            }
            wordDoc.MainDocumentPart.Document.Save();
        }
예제 #2
0
        private static RunProperties AddRunProperties(string textFont, string textSize, bool bold, bool italic)
        {
            var runProperties = new RunProperties();
            var font          = new RunFonts {
                Ascii = textFont
            };
            var size = new FontSize {
                Val = new StringValue(textSize)
            };

            runProperties.AppendChild(font);
            runProperties.AppendChild(size);

            if (bold)
            {
                runProperties.AppendChild(new Bold());
            }

            if (italic)
            {
                runProperties.AppendChild(new Italic());
            }

            return(runProperties);
        }
예제 #3
0
        /**public void getFooterWithPageNumber()
         * {
         *  foreach (Section wordSection in this.adoc.Sections)
         *  {
         *      Range footerRange = wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
         *      footerRange.InlineShapes.AddHorizontalLineStandard();
         *      footerRange.Font.ColorIndex = WdColorIndex.wdDarkRed;
         *      footerRange.Font.Size = 10;
         *      footerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
         *      adoc.Sections[1].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.Add();
         *  }
         * }**/

        public void generateCoverPage(string data)
        {
            body.Append(new Paragraph(new Run(new Break())));
            body.Append(new Paragraph(new Run(new Break())));
            body.Append(new Paragraph(new Run(new Break())));
            body.Append(new Paragraph(new Run(new Break())));

            //heading
            Paragraph           heading = new Paragraph();
            ParagraphProperties hp      = new ParagraphProperties();

            hp.Justification = new Justification()
            {
                Val = JustificationValues.Center
            };
            heading.Append(hp);
            Run           r             = new Run();
            RunProperties runProperties = r.AppendChild(new RunProperties());
            Bold          bold          = new Bold();

            bold.Val = OnOffValue.FromBoolean(true);
            FontSize size = new FontSize();

            size.Val = "60";
            runProperties.AppendChild(bold);
            runProperties.AppendChild(size);
            Text t = new Text(data);

            r.Append(t);
            heading.Append(r);
            body.Append(heading);

            //subheading
            Paragraph           subheading = new Paragraph();
            ParagraphProperties shp        = new ParagraphProperties();

            shp.Justification = new Justification()
            {
                Val = JustificationValues.Center
            };
            subheading.Append(shp);
            Run           rs           = new Run();
            RunProperties rhProperties = rs.AppendChild(new RunProperties());
            Bold          bs           = new Bold();

            bs.Val = OnOffValue.FromBoolean(true);
            FontSize sh = new FontSize();

            sh.Val = "40";
            rhProperties.AppendChild(bs);
            rhProperties.AppendChild(sh);
            Text subhead = new Text("BUSINESS PLAN");

            rs.Append(subhead);
            subheading.Append(rs);
            body.Append(subheading);
            addPageBreak();
        }
예제 #4
0
        protected override WriteResult Write(OpenXMLWpfMathRenderer renderer, CharAtom item)
        {
            bool runCreated = false;
            var  run        = renderer.Peek() as Run;

            if (run == null)
            {
                runCreated = true;
                run        = (Run)renderer.Push(new Run());

                var runProperties = new W.RunProperties();
                runProperties.AppendChild(new W.RunFonts()
                {
                    Ascii = "Cambria Math", HighAnsi = "Cambria Math"
                });

                // Foreground color
                var cf = renderer.PeekForegroundColor();
                if (cf.R != 0 || cf.G != 0 || cf.B != 0)
                {
                    runProperties.AppendChild(new W.Color()
                    {
                        Val = string.Format("{0:X2}{1:X2}{2:X2}", cf.R, cf.G, cf.B)
                    });
                }

                // Background color
                var cb = renderer.PeekBackgroundColor();
                if (cb.R != 255 || cb.G != 255 || cb.B != 255)
                {
                    runProperties.AppendChild(new W.Shading()
                    {
                        Color = "Auto", Fill = string.Format("{0:X2}{1:X2}{2:X2}", cb.R, cb.G, cb.B)
                    });
                }


                run.AppendChild(runProperties);
            }

            var text = new DocumentFormat.OpenXml.Math.Text()
            {
                Text = string.Empty + item.Character
            };

            run.AppendChild(text);


            if (runCreated)
            {
                renderer.PopTo(run);
            }

            return(WriteResult.Completed);
        }
예제 #5
0
        // Add properties with a stykle similar to Heading 3 style at a Run object used by a Paragraph in order to insert text in a Document.
        public RunProperties getHeading3(Run run)
        {
            RunProperties runProperties = run.AppendChild(new RunProperties());
            var           bold          = new Bold();

            bold.Val = OnOffValue.FromBoolean(true);
            var color = new Color {
                Val = "365F91", ThemeColor = ThemeColorValues.Accent1, ThemeShade = "BF"
            };
            var size = new FontSize {
                Val = new StringValue("25")
            };

            runProperties.AppendChild(bold);
            runProperties.AppendChild(color);
            runProperties.AppendChild(size);
            return(runProperties);
        }
예제 #6
0
        // Add the bold style at a Run object used by a Paragraph in order to insert text in a Document.
        public RunProperties getBold(Run run)
        {
            RunProperties runProperties = run.AppendChild(new RunProperties());
            var           bold          = new Bold();

            bold.Val = OnOffValue.FromBoolean(true);
            runProperties.AppendChild(bold);
            return(runProperties);
        }
        /// <summary>
        /// Creates an image paragraph.
        /// </summary>
        /// <param name="relationshipId">The relationship id.</param>
        /// <param name="name">The name.</param>
        /// <param name="description">The description.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <returns>The <see cref="Paragraph" /> containing the image.</returns>
        private DocumentFormat.OpenXml.Wordprocessing.Paragraph CreateImageParagraph(
            string relationshipId, string name, string description, double width, double height)
        {
            // http://msdn.microsoft.com/en-us/library/documentformat.openxml.drawing.extents.aspx
            // http://polymathprogrammer.com/2009/10/22/english-metric-units-and-open-xml/

            // cx (Extent Length)
            // Specifies the length of the extents rectangle in EMUs. This rectangle shall dictate the size of the object as displayed (the result of any scaling to the original object).
            // Example: Consider a DrawingML object specified as follows:
            // <… cx="1828800" cy="200000"/>
            // The cx attributes specifies that this object has a height of 1828800 EMUs (English Metric Units). end example]
            // The possible values for this attribute are defined by the ST_PositiveCoordinate simple type (§20.1.10.42).

            // cy (Extent Width)
            // Specifies the width of the extents rectangle in EMUs. This rectangle shall dictate the size of the object as displayed (the result of any scaling to the original object).
            // Example: Consider a DrawingML object specified as follows:
            // < … cx="1828800" cy="200000"/>
            // The cy attribute specifies that this object has a width of 200000 EMUs (English Metric Units). end example]
            // The possible values for this attribute are defined by the ST_PositiveCoordinate simple type (§20.1.10.42).
            var paragraph1 = new DocumentFormat.OpenXml.Wordprocessing.Paragraph
            {
                RsidParagraphAddition  = "00D91137",
                RsidRunAdditionDefault = "00AC08EB"
            };

            var run1 = new Run();

            var runProperties1 = new RunProperties();
            var noProof1       = new NoProof();

            runProperties1.AppendChild(noProof1);

            var drawing1 = new Drawing();

            var inline1 = new Inline
            {
                DistanceFromTop    = 0U,
                DistanceFromBottom = 0U,
                DistanceFromLeft   = 0U,
                DistanceFromRight  = 0U
            };
            var extent1 = new Extent {
                Cx = 5753100L, Cy = 3600450L
            };

            extent1.Cx = (long)(width * 914400);
            extent1.Cy = (long)(height * 914400);

            var effectExtent1 = new EffectExtent {
                LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L
            };
            var docProperties1 = new DocProperties {
                Id = 1U, Name = name, Description = description
            };

            var nonVisualGraphicFrameDrawingProperties1 = new NonVisualGraphicFrameDrawingProperties();

            var graphicFrameLocks1 = new GraphicFrameLocks {
                NoChangeAspect = true
            };

            graphicFrameLocks1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");

            nonVisualGraphicFrameDrawingProperties1.AppendChild(graphicFrameLocks1);

            var graphic1 = new Graphic();

            graphic1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");

            var graphicData1 = new GraphicData {
                Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
            };

            var picture1 = new Picture();

            picture1.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");

            var nonVisualPictureProperties1 = new NonVisualPictureProperties();
            var nonVisualDrawingProperties1 = new NonVisualDrawingProperties
            {
                Id          = 0U,
                Name        = name,
                Description = description
            };

            var nonVisualPictureDrawingProperties1 = new NonVisualPictureDrawingProperties();
            var pictureLocks1 = new PictureLocks {
                NoChangeAspect = true, NoChangeArrowheads = true
            };

            nonVisualPictureDrawingProperties1.AppendChild(pictureLocks1);

            nonVisualPictureProperties1.AppendChild(nonVisualDrawingProperties1);
            nonVisualPictureProperties1.AppendChild(nonVisualPictureDrawingProperties1);

            var blipFill1 = new BlipFill();

            var blip1 = new Blip {
                Embed = relationshipId
            };

            var blipExtensionList1 = new BlipExtensionList();

            var blipExtension1 = new BlipExtension {
                Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
            };

            var useLocalDpi1 = new UseLocalDpi {
                Val = false
            };

            useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main");

            blipExtension1.AppendChild(useLocalDpi1);

            blipExtensionList1.AppendChild(blipExtension1);

            blip1.AppendChild(blipExtensionList1);
            var sourceRectangle1 = new SourceRectangle();

            var stretch1       = new Stretch();
            var fillRectangle1 = new FillRectangle();

            stretch1.AppendChild(fillRectangle1);

            blipFill1.AppendChild(blip1);
            blipFill1.AppendChild(sourceRectangle1);
            blipFill1.AppendChild(stretch1);

            var shapeProperties1 = new ShapeProperties {
                BlackWhiteMode = BlackWhiteModeValues.Auto
            };

            var transform2D1 = new Transform2D();
            var offset1      = new Offset {
                X = 0L, Y = 0L
            };
            var extents1 = new Extents {
                Cx = extent1.Cx, Cy = extent1.Cy
            };

            transform2D1.AppendChild(offset1);
            transform2D1.AppendChild(extents1);

            var presetGeometry1 = new PresetGeometry {
                Preset = ShapeTypeValues.Rectangle
            };
            var adjustValueList1 = new AdjustValueList();

            presetGeometry1.AppendChild(adjustValueList1);
            var noFill1 = new NoFill();

            var outline1 = new Outline();
            var noFill2  = new NoFill();

            outline1.AppendChild(noFill2);

            shapeProperties1.AppendChild(transform2D1);
            shapeProperties1.AppendChild(presetGeometry1);
            shapeProperties1.AppendChild(noFill1);
            shapeProperties1.AppendChild(outline1);

            picture1.AppendChild(nonVisualPictureProperties1);
            picture1.AppendChild(blipFill1);
            picture1.AppendChild(shapeProperties1);

            graphicData1.AppendChild(picture1);

            graphic1.AppendChild(graphicData1);

            inline1.AppendChild(extent1);
            inline1.AppendChild(effectExtent1);
            inline1.AppendChild(docProperties1);
            inline1.AppendChild(nonVisualGraphicFrameDrawingProperties1);
            inline1.AppendChild(graphic1);

            drawing1.AppendChild(inline1);

            run1.AppendChild(runProperties1);
            run1.AppendChild(drawing1);

            paragraph1.AppendChild(run1);

            return(paragraph1);
        }
예제 #8
0
        /// <summary>
        /// Create a new document, append a single paragraph, set font and color.
        /// - add first paragraph with normal style, color brown
        /// - add second paragraph with normal style, default color
        /// - add a third paragraph with part bold and highlight/shade, part normal.
        /// </summary>
        /// <returns>Is valid document</returns>
        public bool CreateDocumentWithMultipleParagraphAndImage(string pFileName)
        {
            mHasException = false;

            var fileName = Path.Combine(DocumentFolder, pFileName);

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

            using (var document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = document.AddMainDocumentPart();

                mainPart.Document = new Document();

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

                var para    = body.AppendChild(new Paragraph());
                Run runPara = para.AppendChild(new Run());

                // Set the font to Arial to the first Run.
                var runProperties = new RunProperties(
                    new RunFonts()
                {
                    Ascii = "Arial"
                });

                var color = new Color {
                    Val = Helpers.ColorConverter(System.Drawing.Color.Brown)
                };
                runProperties.Append(color);

                Run run = document.MainDocumentPart.Document.Descendants <Run>().First();
                run.PrependChild <RunProperties>(runProperties);

                var paragraphText =
                    "The most basic unit of block-level content within a Word processing document, paragraphs are " +
                    "stored using the <p> element. A paragraph defines a distinct division of content that begins on " +
                    "a new line. A paragraph can contain three pieces of information: optional paragraph properties, " +
                    "inline content (typically runs), and a set of optional revision IDs used to compare the content " +
                    "of two documents.";

                runPara.AppendChild(new Text(paragraphText));

                // add second paragraph
                para = body.AppendChild(new Paragraph());

                runPara = para.AppendChild(new Run());

                paragraphText =
                    "A paragraph's properties are specified via the <pPr>element. Some examples of paragraph properties " +
                    "are alignment, border, hyphenation override, indentation, line spacing, shading, text direction, " +
                    "and widow/orphan control.";

                runPara.AppendChild(new Text(paragraphText));


                // Highlight and bold some text.
                para          = body.AppendChild(new Paragraph());
                run           = para.AppendChild(new Run());
                runProperties = run.AppendChild(new RunProperties());

                runProperties.AppendChild(new Bold {
                    Val = OnOffValue.FromBoolean(true)
                });

                var shading = new Shading()
                {
                    Val  = ShadingPatternValues.Clear,
                    Fill = Helpers.ColorConverter(System.Drawing.Color.Yellow)
                };

                runProperties.Append(shading);

                run.AppendChild(new Text("This is highlight/bold"));

                // back to normal text
                run = para.AppendChild(new Run());
                run.AppendChild(new Text(", and this text is normal."));

                int imageWidth  = 0;
                int imageHeight = 0;

                ImagePart imagePart     = mainPart.AddImagePart(ImagePartType.Jpeg);
                var       imageFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images", "F2.png");

                using (var image = new System.Drawing.Bitmap(imageFileName))
                {
                    imageWidth  = image.Width;
                    imageHeight = image.Height;
                }

                using (var stream = new FileStream(imageFileName, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }

                Helpers.AddImageToBody(document, mainPart.GetIdOfPart(imagePart), imageWidth.PixelToEmu(), imageHeight.PixelToEmu());


                para = body.AppendChild(new Paragraph());
                run  = para.AppendChild(new Run());
                run.AppendChild(new Text("We just inserted an image."));

                mainPart.Document.Save();
            }

            return(Helpers.ValidateWordDocument(fileName) == 0);
        }
        /// <summary>
        /// Creates an image paragraph.
        /// </summary>
        /// <param name="relationshipId">The relationship id.</param>
        /// <param name="name">The name.</param>
        /// <param name="description">The description.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <returns>The <see cref="Paragraph" /> containing the image.</returns>
        private DocumentFormat.OpenXml.Wordprocessing.Paragraph CreateImageParagraph(
            string relationshipId, string name, string description, double width, double height)
        {
            // http://msdn.microsoft.com/en-us/library/documentformat.openxml.drawing.extents.aspx
            // http://polymathprogrammer.com/2009/10/22/english-metric-units-and-open-xml/

            // cx (Extent Length)
            // Specifies the length of the extents rectangle in EMUs. This rectangle shall dictate the size of the object as displayed (the result of any scaling to the original object).
            // Example: Consider a DrawingML object specified as follows:
            // <… cx="1828800" cy="200000"/>
            // The cx attributes specifies that this object has a height of 1828800 EMUs (English Metric Units). end example]
            // The possible values for this attribute are defined by the ST_PositiveCoordinate simple type (§20.1.10.42).

            // cy (Extent Width)
            // Specifies the width of the extents rectangle in EMUs. This rectangle shall dictate the size of the object as displayed (the result of any scaling to the original object).
            // Example: Consider a DrawingML object specified as follows:
            // < … cx="1828800" cy="200000"/>
            // The cy attribute specifies that this object has a width of 200000 EMUs (English Metric Units). end example]
            // The possible values for this attribute are defined by the ST_PositiveCoordinate simple type (§20.1.10.42).
            var paragraph1 = new DocumentFormat.OpenXml.Wordprocessing.Paragraph
                {
                    RsidParagraphAddition = "00D91137",
                    RsidRunAdditionDefault = "00AC08EB"
                };

            var run1 = new Run();

            var runProperties1 = new RunProperties();
            var noProof1 = new NoProof();

            runProperties1.AppendChild(noProof1);

            var drawing1 = new Drawing();

            var inline1 = new Inline
                {
                    DistanceFromTop = 0U,
                    DistanceFromBottom = 0U,
                    DistanceFromLeft = 0U,
                    DistanceFromRight = 0U
                };
            var extent1 = new Extent { Cx = 5753100L, Cy = 3600450L };
            extent1.Cx = (long)(width * 914400);
            extent1.Cy = (long)(height * 914400);

            var effectExtent1 = new EffectExtent { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L };
            var docProperties1 = new DocProperties { Id = 1U, Name = name, Description = description };

            var nonVisualGraphicFrameDrawingProperties1 = new NonVisualGraphicFrameDrawingProperties();

            var graphicFrameLocks1 = new GraphicFrameLocks { NoChangeAspect = true };
            graphicFrameLocks1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");

            nonVisualGraphicFrameDrawingProperties1.AppendChild(graphicFrameLocks1);

            var graphic1 = new Graphic();
            graphic1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");

            var graphicData1 = new GraphicData { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" };

            var picture1 = new Picture();
            picture1.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");

            var nonVisualPictureProperties1 = new NonVisualPictureProperties();
            var nonVisualDrawingProperties1 = new NonVisualDrawingProperties
                {
                    Id = 0U,
                    Name = name,
                    Description = description
                };

            var nonVisualPictureDrawingProperties1 = new NonVisualPictureDrawingProperties();
            var pictureLocks1 = new PictureLocks { NoChangeAspect = true, NoChangeArrowheads = true };

            nonVisualPictureDrawingProperties1.AppendChild(pictureLocks1);

            nonVisualPictureProperties1.AppendChild(nonVisualDrawingProperties1);
            nonVisualPictureProperties1.AppendChild(nonVisualPictureDrawingProperties1);

            var blipFill1 = new BlipFill();

            var blip1 = new Blip { Embed = relationshipId };

            var blipExtensionList1 = new BlipExtensionList();

            var blipExtension1 = new BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" };

            var useLocalDpi1 = new UseLocalDpi { Val = false };
            useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main");

            blipExtension1.AppendChild(useLocalDpi1);

            blipExtensionList1.AppendChild(blipExtension1);

            blip1.AppendChild(blipExtensionList1);
            var sourceRectangle1 = new SourceRectangle();

            var stretch1 = new Stretch();
            var fillRectangle1 = new FillRectangle();

            stretch1.AppendChild(fillRectangle1);

            blipFill1.AppendChild(blip1);
            blipFill1.AppendChild(sourceRectangle1);
            blipFill1.AppendChild(stretch1);

            var shapeProperties1 = new ShapeProperties { BlackWhiteMode = BlackWhiteModeValues.Auto };

            var transform2D1 = new Transform2D();
            var offset1 = new Offset { X = 0L, Y = 0L };
            var extents1 = new Extents { Cx = extent1.Cx, Cy = extent1.Cy };

            transform2D1.AppendChild(offset1);
            transform2D1.AppendChild(extents1);

            var presetGeometry1 = new PresetGeometry { Preset = ShapeTypeValues.Rectangle };
            var adjustValueList1 = new AdjustValueList();

            presetGeometry1.AppendChild(adjustValueList1);
            var noFill1 = new NoFill();

            var outline1 = new Outline();
            var noFill2 = new NoFill();

            outline1.AppendChild(noFill2);

            shapeProperties1.AppendChild(transform2D1);
            shapeProperties1.AppendChild(presetGeometry1);
            shapeProperties1.AppendChild(noFill1);
            shapeProperties1.AppendChild(outline1);

            picture1.AppendChild(nonVisualPictureProperties1);
            picture1.AppendChild(blipFill1);
            picture1.AppendChild(shapeProperties1);

            graphicData1.AppendChild(picture1);

            graphic1.AppendChild(graphicData1);

            inline1.AppendChild(extent1);
            inline1.AppendChild(effectExtent1);
            inline1.AppendChild(docProperties1);
            inline1.AppendChild(nonVisualGraphicFrameDrawingProperties1);
            inline1.AppendChild(graphic1);

            drawing1.AppendChild(inline1);

            run1.AppendChild(runProperties1);
            run1.AppendChild(drawing1);

            paragraph1.AppendChild(run1);

            return paragraph1;
        }