예제 #1
0
        /// <summary>
        /// Creates a line of text for the document
        /// </summary>
        /// <param name="text"></param>
        /// <param name="size"></param>
        /// <param name="bold"></param>
        /// <returns></returns>
        private Run GetText(string text, int size, bool bold = false)
        {
            Run           HighLightRun = new Run();
            RunProperties runPro       = new RunProperties();
            RunFonts      runFont      = new RunFonts()
            {
                Ascii = "Arial", HighAnsi = "Arial"
            };
            FontSize fontSize = new FontSize()
            {
                Val = size.ToString()
            };

            Text runText = new Text()
            {
                Text = text
            };

            runPro.Append(runFont);
            if (bold)
            {
                runPro.Append(new Bold());
            }
            runPro.Append(fontSize);

            HighLightRun.Append(runPro);
            HighLightRun.Append(runText);
            return(HighLightRun);
        }
예제 #2
0
        public void AddText(String text = "", uint fontSize = 12, bool bold = false, bool italic = false)
        {
            Wp.Run           _r  = new Wp.Run();
            Wp.RunProperties _rp = new Wp.RunProperties();
            Wp.RunFonts      _rf = new Wp.RunFonts()
            {
                Ascii         = "Calibri",
                HighAnsi      = "Calibri",
                EastAsia      = "Calibri",
                ComplexScript = "Calibri"
            };
            Wp.FontSize _fs = new Wp.FontSize()
            {
                Val = fontSize.ToString()
            };
            Wp.Languages _l = new Wp.Languages()
            {
                Bidi = "en-us"
            };

            _rp.Append(_rf);
            _rp.Append(_fs);
            _rp.Append(_l);

            if (italic)
            {
                _rp.Append(new Wp.Italic());
            }

            if (bold)
            {
                _rp.Append(new Wp.Bold());
            }

            Wp.Text _t = new Wp.Text();
            _t.Text = text;

            _r.Append(_rp);
            _r.Append(_t);

            this._Paragraph.Append(_r);
        }
예제 #3
0
        /// <summary>
        ///  Initialize new cell header object.
        /// </summary>
        /// <param name="textValue">The content of cell.</param>
        /// <returns>The TableCell object.</returns>
        public virtual TableCell NewTableCellHeader(string textValue, string width = "")
        {
            //create cell object and its properties
            TableCell tableCell = new TableCell();

            TableCellProperties tableCellProperties = new TableCellProperties();

            //ConditionalFormatStyle conditionalFormatStyle = new ConditionalFormatStyle() { Val = "001000000000" };
            if (!string.IsNullOrEmpty(width))
            {
                TableCellWidth tableCellWidth = new TableCellWidth()
                {
                    Width = width, Type = TableWidthUnitValues.Dxa
                };
                tableCellProperties.Append(tableCellWidth);
            }

            //tableCellProperties.Append(hideMark);

            //create paragrpah object and its properties
            Paragraph paragraph = new Paragraph();

            ParagraphProperties paragraphProperties = new ParagraphProperties();
            Justification       justification       = new Justification()
            {
                Val = JustificationValues.Center
            };

            paragraphProperties.Append(justification);

            //create Run and Text
            Run run = new Run();

            DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties = new DocumentFormat.OpenXml.Wordprocessing.RunProperties();
            runProperties.Append(new DocumentFormat.OpenXml.Wordprocessing.Bold());
            Text text = new Text();

            //add content in Text
            text.Text = textValue;
            // Set RunProperties
            run.RunProperties = runProperties;
            //add Text to Run
            run.Append(text);

            //add Run to paragraph
            paragraph.Append(paragraphProperties);
            paragraph.Append(run);

            //add Paragraph to cell
            tableCell.Append(tableCellProperties);
            tableCell.Append(paragraph);

            return(tableCell);
        }
예제 #4
0
        /// <summary>
        /// Create a new document, append a single paragraph, set font and color.
        /// </summary>
        /// <returns>Is valid document</returns>
        public bool CreateDocumentWithSimpleParagraph(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.SandyBrown)
                };
                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));


                mainPart.Document.Save();
            }


            return(Helpers.ValidateWordDocument(fileName) == 0);
        }
예제 #5
0
        private void NextLevel_1(string pFileName)
        {
            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.SandyBrown)
                };
                runProperties.Append(color);

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

                var paragraphText = "Styling paragraph with font color";

                runPara.AppendChild(new Text(paragraphText));


                mainPart.Document.Save();
            }



            Console.WriteLine(Helpers.ValidateWordDocument(fileName));
        }
예제 #6
0
        private static Paragraph GenerateParagraph(string text, bool bold, string textColor)
        {
            Paragraph paragraph1 = new Paragraph()
            {
                RsidParagraphAddition = "004F7104", RsidParagraphProperties = "008F2986", RsidRunAdditionDefault = "004F7104"
            };
            ParagraphProperties paragraphProperties1 = new ParagraphProperties();
            Justification       justification1       = new Justification()
            {
                Val = JustificationValues.Center
            };
            Shading shading = new Shading()
            {
                Color = textColor,
                Fill  = textColor == "000000" ? "FFFFFF" : GetRatingColor(Double.Parse(text))
            };

            paragraphProperties1.Append(justification1);
            paragraphProperties1.Append(shading);

            DocumentFormat.OpenXml.Wordprocessing.Run           run1           = new DocumentFormat.OpenXml.Wordprocessing.Run();
            DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties1 =
                new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.Color()
            {
                Val = textColor
            });

            if (bold)
            {
                runProperties1.Append(new DocumentFormat.OpenXml.Wordprocessing.Bold());
            }

            DocumentFormat.OpenXml.Wordprocessing.Text text1 =
                new DocumentFormat.OpenXml.Wordprocessing.Text
            {
                Text = text
            };

            run1.Append(runProperties1);
            run1.Append(text1);

            paragraph1.Append(paragraphProperties1);
            paragraph1.Append(run1);
            return(paragraph1);
        }
        /// <summary>
        /// Add the text paragraph.
        /// </summary>
        /// <param name="txt">The text.</param>
        /// <param name="boldStyle">if set to <c>true</c> [bold style].</param>
        public void AddTextParagraph(
            string txt,
            bool boldStyle)
        {
            // Assign a reference to the existing document body.
            Body body = _wordProcessingDocument.MainDocumentPart.Document.Body;

            // Add new text.
            Paragraph para = body.AppendChild(new Paragraph());
            Run       run  = para.AppendChild(new Run());

            run.AppendChild(new Text(txt));

            //create RunProperties and append styles
            RunProperties runProperties = new RunProperties();

            if (boldStyle)
            {
                runProperties.Append(new Bold());
            }

            // Set the RunProperties to the RunProperties containing the styles
            run.RunProperties = runProperties;
        }
        /// <summary>
        /// The create 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>
        /// </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.Append(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.Append(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.Append(pictureLocks1);

            nonVisualPictureProperties1.Append(nonVisualDrawingProperties1);
            nonVisualPictureProperties1.Append(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.Append(useLocalDpi1);

            blipExtensionList1.Append(blipExtension1);

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

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

            stretch1.Append(fillRectangle1);

            blipFill1.Append(blip1);
            blipFill1.Append(sourceRectangle1);
            blipFill1.Append(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.Append(offset1);
            transform2D1.Append(extents1);

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

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

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

            outline1.Append(noFill2);

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

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

            graphicData1.Append(picture1);

            graphic1.Append(graphicData1);

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

            drawing1.Append(inline1);

            run1.Append(runProperties1);
            run1.Append(drawing1);

            paragraph1.Append(run1);

            return paragraph1;
        }
예제 #9
0
        public Table GetTable(string tableContext)
        {
            Table tbl = new Table();

            TableProperties properties = new TableProperties();
            TableBorders    borders    = new TableBorders();

            borders.TopBorder = new TopBorder()
            {
                Val = new EnumValue <BorderValues>(BorderValues.Single)
            };
            borders.BottomBorder = new BottomBorder()
            {
                Val = new EnumValue <BorderValues>(BorderValues.Single)
            };
            borders.LeftBorder = new LeftBorder()
            {
                Val = new EnumValue <BorderValues>(BorderValues.Single)
            };
            borders.RightBorder = new RightBorder()
            {
                Val = new EnumValue <BorderValues>(BorderValues.Single)
            };
            borders.InsideHorizontalBorder = new InsideHorizontalBorder()
            {
                Val = new EnumValue <BorderValues>(BorderValues.Single)
            };
            borders.InsideVerticalBorder = new InsideVerticalBorder()
            {
                Val = new EnumValue <BorderValues>(BorderValues.Single)
            };

            TableWidth tableWidth = new TableWidth()
            {
                Width = "5000", Type = TableWidthUnitValues.Pct
            };

            properties.Append(tableWidth);
            properties.Append(borders);

            tbl.Append(properties);

            dynamic Structure = JsonConvert.DeserializeObject(tableContext) as JObject;

            dynamic tableHeading = Structure.settings.columns;
            dynamic tableData    = Structure.data;

            TableRow headingsTableRow = new TableRow();

            foreach (var header in tableHeading)
            {
                Run headerRun = new Run(new Text(header.Name));

                RunProperties headerRunProperties = new RunProperties();
                headerRunProperties.Append(new Bold());
                headerRunProperties.Append(new Justification()
                {
                    Val = JustificationValues.Center
                });
                headerRunProperties.Append(new Color()
                {
                    Val = "FF0000"
                });

                headerRun.Append(headerRunProperties);

                TableCell cell = new TableCell(new Paragraph(headerRun));

                headingsTableRow.Append(cell);
            }

            tbl.AppendChild(headingsTableRow);

            foreach (dynamic record in tableData)
            {
                TableRow recordTableRow = new TableRow();
                foreach (var recordCell in tableHeading)
                {
                    string    value = record[recordCell.Name.ToString()];
                    TableCell cell  = new TableCell(new Paragraph(new Run(new Text(value.ToString()))));

                    recordTableRow.Append(cell);
                }

                tbl.Append(recordTableRow);
            }

            return(tbl);
        }
예제 #10
0
        /// <summary>
        /// Write a text in a paragraph, with some styles
        /// </summary>
        /// <param name="paragraph"></param>
        /// <param name="text"></param>
        /// <param name="fontProperties"></param>
        public void WriteText(Paragraph paragraph, string text, StyleProperties fontProperties)
        {
            Run           run = new Run();
            RunProperties rp  = new RunProperties();

            if (fontProperties.StyleName != null)
            {
                rp.Append(new RunStyle()
                {
                    Val = fontProperties.StyleName
                });
            }
            if (fontProperties.FontName != null)
            {
                rp.Append(new RunFonts()
                {
                    ComplexScript = fontProperties.FontName, Ascii = fontProperties.FontName, HighAnsi = fontProperties.FontName
                });
            }
            else if (fontProperties.UseTemplateHeadingFont)
            {
                rp.Append(new RunFonts()
                {
                    AsciiTheme = ThemeFontValues.MajorHighAnsi, HighAnsiTheme = ThemeFontValues.MajorHighAnsi, ComplexScriptTheme = ThemeFontValues.MajorHighAnsi
                });
            }
            if (fontProperties.FontSize != null)
            {
                rp.Append(new FontSize()
                {
                    Val = fontProperties.FontSize
                });
            }
            if (fontProperties.Bold)
            {
                rp.Append(new Bold());
            }
            if (fontProperties.Italic)
            {
                rp.Append(new Italic());
            }
            if (fontProperties.Underline != UnderlineValues.None)
            {
                rp.Append(new Underline()
                {
                    Val = fontProperties.Underline
                });
            }
            if (fontProperties.Strikeout)
            {
                rp.Append(new Strike());
            }
            if (fontProperties.WriteAs != VerticalPositionValues.Baseline)
            {
                rp.Append(new VerticalTextAlignment()
                {
                    Val = fontProperties.WriteAs
                });
            }
            if (fontProperties.UseThemeColor)
            {
                rp.Append(new DocumentFormat.OpenXml.Wordprocessing.Color()
                {
                    ThemeColor = fontProperties.ThemeColor
                });
            }
            else if (fontProperties.Color != null)
            {
                rp.Append(new DocumentFormat.OpenXml.Wordprocessing.Color()
                {
                    Val = string.Format("#{0:X2}{1:X2}{2:X2}", fontProperties.Color.Value.R, fontProperties.Color.Value.G, fontProperties.Color.Value.B)
                });
            }
            run.Append(rp);
            run.Append(new Text(text)
            {
                Space = SpaceProcessingModeValues.Preserve
            });
            paragraph.Append(run);
        }
예제 #11
0
        /// <summary>追加officeMathMl 到指定的word文档
        /// </summary>
        /// <param name="officeMathMl"></param>
        /// <param name="filePath"></param>
        public void WritOfficeMathMLToWord(string officeMathMl, Run par)
        {
            DocumentFormat.OpenXml.Math.OfficeMath om =
              new DocumentFormat.OpenXml.Math.OfficeMath(officeMathMl);

            foreach (var currentRun in om.Descendants<DocumentFormat.OpenXml.Math.Run>())
            {
                // Add font information to every run.
                DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties2 =
                  new DocumentFormat.OpenXml.Wordprocessing.RunProperties();

                RunFonts runFonts2 = new RunFonts() { Ascii = "Cambria Math", HighAnsi = "Cambria Math" };
                runProperties2.Append(runFonts2);

                currentRun.InsertAt(runProperties2, 0);
            }
            par.Append(om);
        }
예제 #12
0
        /// <summary>追加officeMathMl 到指定的word文档
        /// </summary>
        /// <param name="officeMathMl"></param>
        /// <param name="filePath"></param>
        public void WritOfficeMathMLToWord(string officeMathMl)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Create a OfficeMath instance from the
                // OfficeMathML xml.
                DocumentFormat.OpenXml.Math.OfficeMath om =
                  new DocumentFormat.OpenXml.Math.OfficeMath(officeMathMl);

                // Add the OfficeMath instance to our
                // word template.

                DocumentFormat.OpenXml.Wordprocessing.Paragraph par =
                  _wordDoc.MainDocumentPart.Document.Body.Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().FirstOrDefault();

                foreach (var currentRun in om.Descendants<DocumentFormat.OpenXml.Math.Run>())
                {
                    // Add font information to every run.
                    DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties2 =
                      new DocumentFormat.OpenXml.Wordprocessing.RunProperties();

                    RunFonts runFonts2 = new RunFonts() { Ascii = "Cambria Math", HighAnsi = "Cambria Math" };
                    runProperties2.Append(runFonts2);

                    currentRun.InsertAt(runProperties2, 0);
                }

                par.Append(om);

            }
        }
예제 #13
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);
        }
예제 #14
0
        /// <summary>
        /// The create 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>
        /// </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.Append(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.Append(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.Append(pictureLocks1);

            nonVisualPictureProperties1.Append(nonVisualDrawingProperties1);
            nonVisualPictureProperties1.Append(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.Append(useLocalDpi1);

            blipExtensionList1.Append(blipExtension1);

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

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

            stretch1.Append(fillRectangle1);

            blipFill1.Append(blip1);
            blipFill1.Append(sourceRectangle1);
            blipFill1.Append(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.Append(offset1);
            transform2D1.Append(extents1);

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

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

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

            outline1.Append(noFill2);

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

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

            graphicData1.Append(picture1);

            graphic1.Append(graphicData1);

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

            drawing1.Append(inline1);

            run1.Append(runProperties1);
            run1.Append(drawing1);

            paragraph1.Append(run1);

            return(paragraph1);
        }
예제 #15
0
        public Wordprocessing.Body insertinform()
        {
            Wordprocessing.Body body = new Wordprocessing.Body();
            //Параграф1
            Wordprocessing.Paragraph paragraph1 = new Wordprocessing.Paragraph();
            Wordprocessing.ParagraphProperties paragraphProperties1 = new Wordprocessing.ParagraphProperties();
            Wordprocessing.SpacingBetweenLines spacingBetweenLines1 = new Wordprocessing.SpacingBetweenLines() { After = "0" };
            Wordprocessing.Justification justification1 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center };
            paragraphProperties1.Append(spacingBetweenLines1);
            paragraphProperties1.Append(justification1);
            Wordprocessing.Run run1 = new Wordprocessing.Run();
            Wordprocessing.RunProperties runProperties1 = new Wordprocessing.RunProperties();
            Wordprocessing.RunFonts runFonts2 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" };
            Wordprocessing.Bold bold2 = new Wordprocessing.Bold();
            Wordprocessing.FontSize fontSize2 = new Wordprocessing.FontSize() { Val = "24" };
            runProperties1.Append(runFonts2);
            runProperties1.Append(bold2);
            runProperties1.Append(fontSize2);
            Wordprocessing.Text text1 = new Wordprocessing.Text();
            text1.Text = "ФГБОУВПО \"ПЕРМСКИЙ ГОСУДАРСТВЕННЫЙ НАЦИОНАЛЬНЫЙ ИССЛЕДОВАТЕЛЬСКИЙ УНИВЕРСИТЕТ\"";
            run1.Append(runProperties1);
            run1.Append(text1);
            paragraph1.Append(paragraphProperties1);
            paragraph1.Append(run1);

            //Параграф2
            Wordprocessing.Paragraph paragraph2 = new Wordprocessing.Paragraph();

            Wordprocessing.ParagraphProperties paragraphProperties2 = new Wordprocessing.ParagraphProperties();
            Wordprocessing.SpacingBetweenLines spacingBetweenLines2 = new Wordprocessing.SpacingBetweenLines() { After = "0" };
            Wordprocessing.Justification justification2 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center };
            paragraphProperties2.Append(spacingBetweenLines2);
            paragraphProperties2.Append(justification2);
            Wordprocessing.Run run2 = new Wordprocessing.Run();

            Wordprocessing.RunProperties runProperties2 = new Wordprocessing.RunProperties();
            Wordprocessing.RunFonts runFonts4 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" };
            Wordprocessing.FontSize fontSize4 = new Wordprocessing.FontSize() { Val = "24" };

            runProperties2.Append(runFonts4);
            runProperties2.Append(fontSize4);
            Wordprocessing.Text text2 = new Wordprocessing.Text();
            text2.Text = "Механико-математический факультет ";

            run2.Append(runProperties2);
            run2.Append(text2);

            Wordprocessing.Run run3 = new Wordprocessing.Run();

            Wordprocessing.RunProperties runProperties3 = new Wordprocessing.RunProperties();
            Wordprocessing.RunFonts runFonts5 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" };
            Wordprocessing.FontSize fontSize5 = new Wordprocessing.FontSize() { Val = "24" };
            runProperties3.Append(runFonts5);
            runProperties3.Append(fontSize5);
            Wordprocessing.Break break1 = new Wordprocessing.Break();
            Wordprocessing.Text text3 = new Wordprocessing.Text();
            text3.Text = "очная форма обучения";

            run3.Append(runProperties3);
            run3.Append(break1);
            run3.Append(text3);

            paragraph2.Append(paragraphProperties2);
            paragraph2.Append(run2);
            paragraph2.Append(run3);

            //Параграф2
            Wordprocessing.Paragraph paragraph3 = new Wordprocessing.Paragraph() { RsidParagraphAddition = "004D49E1", RsidParagraphProperties = "004D49E1", RsidRunAdditionDefault = "004D49E1" };

            Wordprocessing.ParagraphProperties paragraphProperties3 = new Wordprocessing.ParagraphProperties();
            Wordprocessing.SpacingBetweenLines spacingBetweenLines3 = new Wordprocessing.SpacingBetweenLines() { After = "0" };
            Wordprocessing.Justification justification3 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center };
            paragraphProperties3.Append(spacingBetweenLines3);
            paragraphProperties3.Append(justification3);
            Wordprocessing.Run run4 = new Wordprocessing.Run();

            Wordprocessing.RunProperties runProperties4 = new Wordprocessing.RunProperties();
            Wordprocessing.RunFonts runFonts7 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" };
            Wordprocessing.Bold bold4 = new Wordprocessing.Bold();

            runProperties4.Append(runFonts7);
            runProperties4.Append(bold4);
            Wordprocessing.Text text4 = new Wordprocessing.Text();
            text4.Text = "ЭКЗАМЕНАЦИОННАЯ ВЕДОМОСТЬ";
            run4.Append(runProperties4);
            run4.Append(text4);

            Wordprocessing.Run run5 = new Wordprocessing.Run();
            Wordprocessing.Break break2 = new Wordprocessing.Break();
            run5.Append(break2);

            paragraph3.Append(paragraphProperties3);
            paragraph3.Append(run4);
            paragraph3.Append(run5);

            body.Append(paragraph1);
            body.Append(paragraph2);
            body.Append(paragraph3);
            return body;
        }
예제 #16
0
        public void CreateWordDoc(DataTable data, decimal t, string user)
        {
            string pathUser     = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            string pathDownload = Path.Combine(pathUser, "Downloads");
            //string pathDownload = Server.MapPath("~/Content/");
            decimal total = t;

            try
            {
                //Set the current directory.
                Directory.SetCurrentDirectory(pathDownload);
            }
            catch (DirectoryNotFoundException e)
            {
                Console.WriteLine("The specified directory does not exist. {0}", e);
            }

            WordprocessingDocument doc         = WordprocessingDocument.Create("ExpenseReport.docx", WordprocessingDocumentType.Document);
            MainDocumentPart       mainDocPart = doc.AddMainDocumentPart();

            mainDocPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
            DocumentFormat.OpenXml.Wordprocessing.Body body = new DocumentFormat.OpenXml.Wordprocessing.Body();
            mainDocPart.Document.Append(body);
            DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();

            //border
            TableProperties tblProp = new TableProperties(
                new TableBorders(
                    new InsideHorizontalBorder()
            {
                Val = new EnumValue <BorderValues>(BorderValues.BasicThinLines), Size = 10
            })
                );

            // Append the TableProperties object to the empty table.
            table.AppendChild <TableProperties>(tblProp);

            //setting header
            DocumentFormat.OpenXml.Wordprocessing.TableRow      tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            DocumentFormat.OpenXml.Wordprocessing.RunProperties rp = new DocumentFormat.OpenXml.Wordprocessing.RunProperties();
            rp.Append(new DocumentFormat.OpenXml.Wordprocessing.Color()
            {
                Val = "#FF0000"
            });
            RunFonts rFont1 = new RunFonts();

            rFont1.Ascii = "Arial";
            rp.Append(rFont1);
            rp.Append(new Bold());
            rp.Append(new DocumentFormat.OpenXml.Wordprocessing.FontSize()
            {
                Val = "28"
            });

            DocumentFormat.OpenXml.Wordprocessing.Run run = new DocumentFormat.OpenXml.Wordprocessing.Run();
            run.RunProperties = rp;
            run.Append(new Text("Expense Report for " + user));
            DocumentFormat.OpenXml.Wordprocessing.Paragraph           para = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(run);
            DocumentFormat.OpenXml.Wordprocessing.TableCellProperties tcpp = new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties();
            tcpp.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellWidth {
                Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Dxa, Width = "2200"
            });
            GridSpan gs = new GridSpan();

            gs.Val = 5;
            tcpp.Append(gs);
            DocumentFormat.OpenXml.Wordprocessing.TableCell tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell(tcpp, para);
            tr.Append(tc);
            table.Append(tr);

            DocumentFormat.OpenXml.Wordprocessing.TableRow row_header = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            foreach (DataColumn column in data.Columns)
            {
                DocumentFormat.OpenXml.Wordprocessing.TableCell cell = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                cell.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(
                                new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(column.ToString()))));
                cell.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties(new DocumentFormat.OpenXml.Wordprocessing.TableCellWidth {
                    Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Dxa, Width = "2200"
                }));
                row_header.Append(cell);
            }

            table.Append(row_header);

            for (int i = 0; i < data.Rows.Count; ++i)
            {
                DocumentFormat.OpenXml.Wordprocessing.TableRow row = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                for (int j = 0; j < data.Columns.Count; j++)
                {
                    DocumentFormat.OpenXml.Wordprocessing.TableCell cell = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                    cell.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data.Rows[i][j].ToString()))));
                    cell.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties(new DocumentFormat.OpenXml.Wordprocessing.TableCellWidth {
                        Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Dxa, Width = "2200"
                    }));
                    row.Append(cell);
                }
                table.Append(row);
            }
            body.Append(table);

            Run       run1  = new Run();
            Paragraph para1 = new Paragraph(run1);

            run1.AppendChild(new Text("The total Expenditure is " + total));
            body.Append(para1);
            doc.MainDocumentPart.Document.Save();
            doc.Dispose();
        }