예제 #1
1
        //Добавление комментария
        public void AddCommentOnParagraph(DocumentFormat.OpenXml.Wordprocessing.Paragraph comPar, string comment)
        {
            DocumentFormat.OpenXml.Wordprocessing.Comments comments = null;
                string id = "0";

                // Verify that the document contains a
                // WordProcessingCommentsPart part; if not, add a new one.
                if (document.MainDocumentPart.GetPartsCountOfType<WordprocessingCommentsPart>() > 0)
                {
                    comments =
                        document.MainDocumentPart.WordprocessingCommentsPart.Comments;
                    if (comments.HasChildren == true)
                    {
                        // Obtain an unused ID.
                        id = comments.Descendants<DocumentFormat.OpenXml.Wordprocessing.Comment>().Select(e => e.Id.Value).Max() + 1;
                    }
                }
                else
                {
                    // No WordprocessingCommentsPart part exists, so add one to the package.
                    WordprocessingCommentsPart commentPart = document.MainDocumentPart.AddNewPart<WordprocessingCommentsPart>();
                    commentPart.Comments = new DocumentFormat.OpenXml.Wordprocessing.Comments();
                    comments = commentPart.Comments;
                }

                // Compose a new Comment and add it to the Comments part.
                DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new Text(comment)));
                DocumentFormat.OpenXml.Wordprocessing.Comment cmt =
                    new DocumentFormat.OpenXml.Wordprocessing.Comment()
                    {
                        Id = id,
                        Author = "FRChecking System",
                        Date = DateTime.Now
                    };
                cmt.AppendChild(p);
                comments.AppendChild(cmt);
                comments.Save();

                // Specify the text range for the Comment.
                // Insert the new CommentRangeStart before the first run of paragraph.
                comPar.InsertBefore(new CommentRangeStart() { Id = id }, comPar.GetFirstChild<DocumentFormat.OpenXml.Wordprocessing.Run>());

                // Insert the new CommentRangeEnd after last run of paragraph.
                var cmtEnd = comPar.InsertAfter(new CommentRangeEnd() { Id = id }, comPar.Elements<DocumentFormat.OpenXml.Wordprocessing.Run>().Last());

                // Compose a run with CommentReference and insert it.
                comPar.InsertAfter(new DocumentFormat.OpenXml.Wordprocessing.Run(new CommentReference() { Id = id }), cmtEnd);
        }
        public override IEnumerable<OpenXmlElement> ToOpenXmlElements(DocumentFormat.OpenXml.Packaging.MainDocumentPart mainDocumentPart)
        {
            var result = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();

            var paragraphProperties = new ParagraphProperties();

            var numberingProperties = new NumberingProperties();
            var numberingLevelReference = new NumberingLevelReference() { Val = 0 };

            NumberingId numberingId;
            ParagraphStyleId paragraphStyleId;
            if (Parent is OrderedListFormattedElement)
            {
                paragraphStyleId = new ParagraphStyleId() { Val = "NumberedList" };
                numberingId = new NumberingId() { Val = ((OrderedListFormattedElement)Parent).NumberingInstanceId };

                var indentation = new Indentation() { Left = "1440", Hanging = "720" };
                paragraphProperties.Append(indentation);
            }
            else
            {
                paragraphStyleId = new ParagraphStyleId() { Val = "UnorderedListStyle" };
                numberingId = new NumberingId() { Val = 3 };
            }

            numberingProperties.Append(numberingLevelReference);
            numberingProperties.Append(numberingId);

            var spacingBetweenLines= new SpacingBetweenLines() { After = "100", AfterAutoSpacing = true };

            paragraphProperties.Append(paragraphStyleId);
            paragraphProperties.Append(numberingProperties);
            paragraphProperties.Append(spacingBetweenLines);
            result.Append(paragraphProperties);

            ForEachChild(x =>
            {
                if (x is TextFormattedElement)
                {
                    result.Append(
                        new DocumentFormat.OpenXml.Wordprocessing.Run(x.ToOpenXmlElements(mainDocumentPart))
                    );

                }
                else
                {
                    result.Append(x.ToOpenXmlElements(mainDocumentPart));
                }
            });

            return new List<OpenXmlElement> { result };
        }
        public override IParagraph Add()
        {
            OpenXmlSdk.Paragraph openXmlParagraph = new OpenXmlSdk.Paragraph();
            _textDocument.InnerObject.MainDocumentPart.Document.Body.Append(openXmlParagraph);

            OpenXmlSdkParagraph paragraph = new OpenXmlSdkParagraph(_textDocument, openXmlParagraph);

            if (paragraph != null)
            {
                Add(paragraph);
            }

            return paragraph;
        }
예제 #4
0
        public void W054_Load_Save_Strict()
        {
            using (var stream = GetStream(TestFiles.Strict01, true))
                using (var doc = WordprocessingDocument.Open(stream, true))
                {
                    var body    = doc.MainDocumentPart.Document.Body;
                    var para    = body.Elements <W.Paragraph>().First();
                    var newPara = new W.Paragraph(
                        new W.Run(
                            new W.Text("Test")));
                    para.InsertBeforeSelf(newPara);

                    var v    = new OpenXmlValidator(FileFormatVersions.Office2013);
                    var errs = v.Validate(doc);
                }
        }
예제 #5
0
        private WordParagraph GetTableNumberParagraph()
        {
            var paragraph = new WordParagraph();
            var pp        = new ParagraphProperties()
            {
                Justification = new Justification()
                {
                    Val = JustificationValues.Right
                },
                SpacingBetweenLines = new SpacingBetweenLines()
                {
                    Before   = "100",
                    After    = "100",
                    Line     = "300",
                    LineRule = LineSpacingRuleValues.Exact
                }
            };

            paragraph.Append(pp);

            var run           = new Run();
            var runProperties = new RunProperties(new RunFonts
            {
                HighAnsi = new StringValue("Times New Roman"),
                Ascii    = "Times New Roman"
            })
            {
                Color = new Color()
                {
                    Val = renderData.RenderSettings.DefaultColor
                },
                FontSize = new FontSize()
                {
                    Val = renderData.RenderSettings.DefaultTextSize
                },
            };

            run.PrependChild(runProperties);

            var text = new Text("Таблица (номер)");

            run.Append(text);
            paragraph.Append(run);

            return(paragraph);
        }
예제 #6
0
        public static void createDocument(string filepath)
        {
            // Create a document by supplying the filepath.
            using (WordprocessingDocument wordDocument =
                       WordprocessingDocument.Create(filepath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
            {
                // Add a main document part.
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                // Create the document structure and add some text.
                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());
                DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
                DocumentFormat.OpenXml.Wordprocessing.Run       run  = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
                run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("HQ - QUANTUM 2012"));
            }
        }
예제 #7
0
        private WordParagraph GetTableNameParagraph()
        {
            var paragraph = new WordParagraph();
            var pp        = new ParagraphProperties()
            {
                Justification = new Justification()
                {
                    Val = JustificationValues.Center
                },
                SpacingBetweenLines = new SpacingBetweenLines()
                {
                    Before   = "100",
                    After    = "100",
                    Line     = "300",
                    LineRule = LineSpacingRuleValues.Exact
                }
            };

            paragraph.Append(pp);

            var run           = new Run();
            var runProperties = new RunProperties(new RunFonts
            {
                HighAnsi = new StringValue(renderData.RenderSettings.FontFamily),
                Ascii    = renderData.RenderSettings.FontFamily
            })
            {
                Color = new Color()
                {
                    Val = renderData.RenderSettings.DefaultColor
                },
                FontSize = new FontSize()
                {
                    Val = renderData.RenderSettings.DefaultTextSize
                },
            };

            run.PrependChild(runProperties);

            var text = new Text(Table.Name);

            run.Append(text);
            paragraph.Append(run);

            return(paragraph);
        }
예제 #8
0
        public void InvalidHr()
        {
            using (MemoryStream mem = new MemoryStream())
            {
                WordDocument doc = new WordDocument(mem);

                doc.Process(new HtmlParser("<div>1</div><hr><div>2</div>"));

                Assert.IsNotNull(doc.Document.Body);
                Assert.AreEqual(3, doc.Document.Body.ChildElements.Count);

                Word.Paragraph para = doc.Document.Body.ChildElements[0] as Word.Paragraph;

                Assert.IsNotNull(para);
                Assert.AreEqual(1, para.ChildElements.Count);

                Word.Run run = para.ChildElements[0] as Word.Run;

                Assert.IsNotNull(run);
                Assert.AreEqual(1, run.ChildElements.Count);

                Word.Text text = run.ChildElements[0] as Word.Text;

                Assert.IsNotNull(text);
                Assert.AreEqual("1", text.InnerText);

                para = doc.Document.Body.ChildElements[2] as Word.Paragraph;

                Assert.IsNotNull(para);
                Assert.AreEqual(1, para.ChildElements.Count);

                run = para.ChildElements[0] as Word.Run;

                Assert.IsNotNull(run);
                Assert.AreEqual(1, run.ChildElements.Count);

                text = run.ChildElements[0] as Word.Text;

                Assert.IsNotNull(text);
                Assert.AreEqual("2", text.InnerText);

                OpenXmlValidator validator = new OpenXmlValidator();
                var errors = validator.Validate(doc.WordprocessingDocument);
                Assert.AreEqual(0, errors.Count());
            }
        }
예제 #9
0
        /// <summary>
        /// Append SubDocument at end of current doc
        /// </summary>
        /// <param name="content"></param>
        /// <param name="withPageBreak">If true insert a page break before.</param>
        public void AppendSubDocument(Stream content, bool withPageBreak)
        {
            if (wdDoc == null)
            {
                throw new InvalidOperationException("Document not loaded");
            }

            AlternativeFormatImportPart formatImportPart = wdMainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML);

            formatImportPart.FeedData(content);

            AltChunk altChunk = new AltChunk();

            altChunk.Id = wdMainDocumentPart.GetIdOfPart(formatImportPart);

            OpenXmlElement lastElement = wdMainDocumentPart.Document.Body.LastChild;

            if (lastElement is SectionProperties)
            {
                lastElement.InsertBeforeSelf(altChunk);
                if (withPageBreak)
                {
                    SectionProperties sectionProps = (SectionProperties)lastElement.Clone();
                    var p   = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
                    var ppr = new DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties();
                    p.AppendChild(ppr);
                    ppr.AppendChild(sectionProps);
                    altChunk.InsertBeforeSelf(p);
                }
            }
            else
            {
                lastElement.InsertAfterSelf(altChunk);
                if (withPageBreak)
                {
                    Paragraph p = new Paragraph(
                        new Run(
                            new Break()
                    {
                        Type = BreakValues.Page
                    }));
                    altChunk.InsertBeforeSelf(p);
                }
            }
        }
예제 #10
0
        public static WP.Paragraph LambdaRefParagraph(float lambda, float lambdaRef, float Ry, float E)
        {
            var p          = new WP.Paragraph();
            var officeMath = new OfficeMath();

            var bar           = new DocumentFormat.OpenXml.Math.Bar();
            var barProperties = new BarProperties();
            var position      = new Position()
            {
                Val = VerticalJustificationValues.Top
            };

            barProperties.Append(position);

            var bas = new Base(new Run(new Text("λ")));

            bar.Append(barProperties, bas);

            officeMath.Append(
                bar,
                GenerateRunWithText(" = λ ∙ "),
                CreateRadical(
                    CreateFraction(
                        new List <OpenXmlElement> {
                Index("R", "y")
            },
                        new List <OpenXmlElement> {
                GenerateRunWithText("E")
            })),
                GenerateRunWithText($" = {lambda} "),

                CreateRadical(
                    CreateFraction(
                        new List <OpenXmlElement> {
                GenerateRunWithText($"{Ry}")
            },
                        new List <OpenXmlElement> {
                GenerateRunWithText($"{E}")
            })),
                GenerateRunWithText(" = "),
                GenerateRunWithText($" = {lambdaRef}")
                );
            p.AppendChild(officeMath);
            return(p);
        }
        public OpenXmlCompositeElement GetElement()
        {
            var paragraph = new WordParagraph();
            var pp        = new ParagraphProperties()
            {
                Justification = new Justification()
                {
                    Val = JustificationValues.Center
                },
                SpacingBetweenLines = new SpacingBetweenLines()
                {
                    Before   = "100",
                    After    = "100",
                    Line     = "250",
                    LineRule = LineSpacingRuleValues.Exact
                }
            };

            paragraph.Append(pp);

            var run           = new Run();
            var runProperties = new RunProperties(new RunFonts
            {
                HighAnsi = new StringValue(renderData.RenderSettings.FontFamily)
            })
            {
                Color = new Color()
                {
                    Val = renderData.RenderSettings.DefaultColor
                },
                FontSize = new FontSize()
                {
                    Val = "27"
                },
            };

            run.PrependChild(runProperties);

            var wordText = new Text(Text);

            run.Append(wordText);
            paragraph.Append(run);

            return(paragraph);
        }
예제 #12
0
        public void W016_InsertAfterSelf()
        {
            using (var stream = GetStream(TestFiles.Document))
                using (var doc = WordprocessingDocument.Open(stream, false))
                {
                    var mdp     = doc.MainDocumentPart;
                    var newPara = new W.Paragraph(
                        new W.Run(
                            new W.Text("Hello")));
                    var firstPara = mdp.Document.Body.Elements <W.Paragraph>().FirstOrDefault();

                    firstPara.InsertAfterSelf(newPara);

                    var v = new OpenXmlValidator(FileFormatVersions.Office2013);

                    Assert.Equal(2, v.Validate(doc).Count());
                }
        }
예제 #13
0
        private void AddLinks()
        {
            WordprocessingDocument wordprocessingDocument =
                WordprocessingDocument.Open(filepath, true);
            Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

            DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
            DocumentFormat.OpenXml.Wordprocessing.Run       run  = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());

            System.Random rand = new System.Random();
            int           r    = rand.Next(1, 11111111);

            res = res.Replace("<w:numId w:val=\"1\" />", "<w:numId w:val=\"" + r + "\" />");

            body.InnerXml += res;

            wordprocessingDocument.Close();
        }
예제 #14
0
        public Paragraph CreateParagraph(string paragraphStyleName)
        {
            if (string.IsNullOrEmpty(paragraphStyleName))
            {
                return(CreateParagraph());
            }

            ParagraphProperties paraProp = new ParagraphProperties();

            paraProp.Append(new ParagraphStyleId()
            {
                Val = paragraphStyleName
            });
            var para = new Paragraph();

            para.Append(paraProp);
            _body.Append(para);
            return(para);
        }
예제 #15
0
        /// <summary>
        /// Gets a list in OOXMLFormat.
        /// This is returned as a list as an object may have multiple paragraphs.
        /// </summary>
        /// <param name="listId">The id of the listvin the numbering.</param>
        /// <returns>List of lisr in OOXML Format.</returns>
        public virtual List <OOXMLParagraph> GetOOXMLList(int listId)
        {
            List <OOXMLParagraph> list = new List <OOXMLParagraph>();


            foreach (var item in Items)
            {
                var element = new OOXMLParagraph();

                ParagraphProperties paragraphProperties1 = new ParagraphProperties();
                ParagraphStyleId    paragraphStyleId1    = new ParagraphStyleId()
                {
                    Val = "ListParagraph"
                };

                NumberingProperties     numberingProperties1     = new NumberingProperties();
                NumberingLevelReference numberingLevelReference1 = new NumberingLevelReference()
                {
                    Val = item.Level
                };
                NumberingId numberingId1 = new NumberingId()
                {
                    Val = listId
                };

                numberingProperties1.Append(numberingLevelReference1);
                numberingProperties1.Append(numberingId1);

                paragraphProperties1.Append(paragraphStyleId1);
                paragraphProperties1.Append(numberingProperties1);

                Run  run1 = new Run();
                Text text = new Text();
                text.Text = item.Text;

                run1.Append(text);

                element.Append(paragraphProperties1);
                element.Append(run1);
                list.Add(element);
            }
            return(list);
        }
예제 #16
0
        public WordParagraph GetLastParagraphOfThePage()
        {
            var paragraph = new WordParagraph();
            var pp        = new ParagraphProperties()
            {
                Justification = new Justification()
                {
                    Val = JustificationValues.Center
                },
            };

            paragraph.Append(pp);

            var run = new Run(new LastRenderedPageBreak(), new Break()
            {
                Type = BreakValues.Page
            });
            var runProperties = new RunProperties(new RunFonts
            {
                HighAnsi = new StringValue(
                    renderData.RenderSettings.FontFamily)
            })
            {
                Color = new Color()
                {
                    Val = renderData.RenderSettings.DefaultColor
                },
                FontSize = new FontSize()
                {
                    Val = "30"
                }
            };

            run.PrependChild(runProperties);

            var wordText = new Text();

            run.Append(wordText);
            paragraph.Append(run);

            return(paragraph);
        }
예제 #17
0
        public void W015_InsertBeforeSelf()
        {
            using (var stream = GetStream(TestFiles.Document))
                using (var doc = WordprocessingDocument.Open(stream, false))
                {
                    var mdp     = doc.MainDocumentPart;
                    var newPara = new W.Paragraph(
                        new W.Run(
                            new W.Text("Hello")));
                    var firstPara = mdp.Document.Body.Elements <W.Paragraph>().FirstOrDefault();

                    firstPara.InsertBeforeSelf(newPara);

                    var v    = new OpenXmlValidator(FileFormatVersions.Office2013);
                    var errs = v.Validate(doc);
                    var cnt  = errs.Count();

                    Assert.True(cnt == 416 || cnt == 2); // v3.0 correctly reports fewer errors than v2.5.1
                }
        }
예제 #18
0
        public static Wordprocessing.TableCell AddCell(this Wordprocessing.TableRow tableRow, string value)
        {
            Wordprocessing.TableCell tableCell = new Wordprocessing.TableCell();
            Wordprocessing.Paragraph par = new Wordprocessing.Paragraph();
            Wordprocessing.ParagraphProperties parprop = new Wordprocessing.ParagraphProperties();
            Wordprocessing.Justification justification1 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center };
            Wordprocessing.SpacingBetweenLines spacingBetweenLines2 = new Wordprocessing.SpacingBetweenLines() { After = "0"};
            parprop.Append(spacingBetweenLines2);
            parprop.Append(justification1);
            par.Append(parprop);

            Wordprocessing.Run run = new Wordprocessing.Run() ;
            Wordprocessing.Text text = new Wordprocessing.Text(value);
            run.Append(text);
            par.Append(run);
            tableCell.Append(par);
            tableRow.Append(tableCell);

            return tableCell;
        }
예제 #19
0
        public void AddTheListOfSourcesUsed(string filepath)
        {
            if (!File.Exists(filePath1.Text))
            {
                Application.Current.Shutdown();
            }
            WordprocessingDocument wordprocessingDocument =
                WordprocessingDocument.Open(filepath, true);
            Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

            DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
            DocumentFormat.OpenXml.Wordprocessing.Run       run  = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
            text = body.InnerText;
            FileStream fl = new FileStream(@"NEWXML.xml", FileMode.OpenOrCreate);

            byte[] innerxml = Encoding.UTF8.GetBytes(body.InnerXml);
            fl.Write(innerxml, 0, innerxml.Length);
            fl.Close();
            wordprocessingDocument.Close();
        }
예제 #20
0
        private Paragraph StudentInformationSection()
        {
            var run       = new Run();
            var paragraph = new Paragraph();

            var studentIdText = new Text("ID:______________ ");
            var nameText      = new Text("Nombre:__________________________ ");
            var dateText      = new Text("Fecha:______________________");

            studentIdText.Space = SpaceProcessingModeValues.Preserve;
            nameText.Space      = SpaceProcessingModeValues.Preserve;

            run.Append(studentIdText);
            run.Append(nameText);
            run.Append(dateText);

            paragraph.Append(run);

            return(paragraph);
        }
예제 #21
0
        public void W017_InsertBefore_InsertAfter()
        {
            using (var stream = GetStream(TestFiles.Document))
                using (var doc = WordprocessingDocument.Open(stream, false))
                {
                    var mdp     = doc.MainDocumentPart;
                    var newPara = new W.Paragraph(
                        new W.Run(
                            new W.Text("Hello")));
                    var firstPara = mdp.Document.Body.Elements <W.Paragraph>().FirstOrDefault();
                    mdp.Document.Body.InsertBefore(newPara, firstPara);

                    var newPara2 = (OpenXmlElement)newPara.Clone();
                    mdp.Document.Body.InsertAfter(newPara2, firstPara);

                    var v = new OpenXmlValidator(FileFormatVersions.Office2013);

                    Assert.Single(v.Validate(doc));
                }
        }
예제 #22
0
        public OpenXmlCompositeElement GetElement()
        {
            var paragraph = new WordParagraph();
            var pp        = new ParagraphProperties()
            {
                Justification = new Justification()
                {
                    Val = JustificationValues.Center
                }
            };

            paragraph.Append(pp);
            var run           = new Run();
            var runProperties = new RunProperties();

            run.PrependChild(runProperties);
            paragraph.Append(run);

            return(paragraph);
        }
        public void MakeResettlementDocument(Evacuated ev, Adress ad, string path)
        {
            if (Template != null)
            {
                //Body body = new Body(Template.MainDocumentPart.Document.Body.Elements().ToList());

                Document = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document);
                Document.AddMainDocumentPart();
                var s = Template.MainDocumentPart.Document.InnerXml;

                s = s.Replace("EvacuatedSurname", ev.Surname);
                s = s.Replace("EvacuatedName", ev.Name);
                s = s.Replace("EvacuatedPatronomic", ev.Patronomic);
                s = s.Replace("EvacuatedDocNum", ev.NumberOfDocument);
                s = s.Replace("EvacuatedDocData", ev.DocumentData);
                 s = s.Replace("EvacuatedDateOfBirth", ev.DateOfBirth.ToString("d"));
                 if (ev.DocumentType != null) s = s.Replace("EvacuatedDocType", ev.DocumentType.TypeName);
                 else s=s.Replace("EvacuatedDocType", "_________");

                //for adress
                s = s.Replace("AdressOwnerName", ad.OwnerName);
                if(ad.Village!=null&&ad.Street!=null)s = s.Replace("AdressAdress", ad.Village.Name + " " + ad.Street.Title + " " + ad.HouseNumber);
                s = s.Replace("AdressSquare", ad.Square.ToString());
                s = s.Replace("AdressOwnerDocData", ad.OwnerDocData);

                Document.MainDocumentPart.AddPart(Template.MainDocumentPart.StyleDefinitionsPart);

                Paragraph p = new Paragraph(new Run(new Text("")));

                Document.MainDocumentPart.Document =
                      new Document(
                        new Body(
                         p));

                Document.MainDocumentPart.Document.InnerXml = s;

                Document.MainDocumentPart.Document.Save();
                Document.Close();

            }
        }
예제 #24
0
        public static WP.Paragraph GenerateParagraphWithAxialCompressionFormula(Bar bar, float Ry, float fi, bool moment)
        {
            var            p          = new WP.Paragraph();
            var            officeMath = new OfficeMath();
            OpenXmlElement fitext;

            if (moment)
            {
                fitext = Index("φ", "e");
            }
            else
            {
                fitext = GenerateRunWithText("φ");
            }


            var fractionFormula = CreateFraction(
                new List <OpenXmlElement> {
                GenerateRunWithText("N")
            },
                new List <OpenXmlElement> {
                GenerateRunWithText("A∙"), fitext, GenerateRunWithText("∙"), Index("R", "y")
            });

            var fraction = CreateFraction(
                new List <OpenXmlElement> {
                GenerateRunWithText($"{Math.Abs(bar.ActualForce)}")
            },
                new List <OpenXmlElement> {
                GenerateRunWithText($"{bar.Section.Area}∙{fi}∙{Ry}∙"), Power("10", "2"),
            });


            officeMath.Append(
                fractionFormula,
                new Run(new Text(" = ")),
                fraction,
                new Run(new Text($" = {bar.CalcResult} " + (bar.CalcResult <= 1 ? "≤" : ">") + " 1")));
            p.AppendChild(officeMath);
            return(p);
        }
예제 #25
0
 public void CreateNewDoc(string resumsPath, string ResumContent, string filename)
 {
     using (WordprocessingDocument document = WordprocessingDocument.Create(resumsPath, WordprocessingDocumentType.Document))
     {
         MainDocumentPart mainPart = document.AddMainDocumentPart();
         mainPart.Document = new Document(new Body());
         Body body = new Body();
         //Create paragraph
         DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph     = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
         DocumentFormat.OpenXml.Wordprocessing.Run       run_paragraph = new DocumentFormat.OpenXml.Wordprocessing.Run();
         // we want to put that text into the output document
         Text text_paragraph = new Text(ResumContent);
         //Append elements appropriately.
         run_paragraph.Append(text_paragraph);
         paragraph.Append(run_paragraph);
         body.Append(paragraph);
         mainPart.Document.Append(body);
         document.MainDocumentPart.Document.Save();
         document.Close();
     }
 }
예제 #26
0
        internal static void TestTableCell(this Word.TableCell cell, Int32 childCount, string content)
        {
            Assert.IsNotNull(cell);
            Assert.AreEqual(childCount, cell.ChildElements.Count);

            Word.Paragraph para = cell.ChildElements[0] as Word.Paragraph;

            Assert.IsNotNull(para);
            Assert.AreEqual(1, para.ChildElements.Count);

            Word.Run run = para.ChildElements[0] as Word.Run;

            Assert.IsNotNull(run);
            Assert.AreEqual(1, run.ChildElements.Count);

            Word.Text text = run.ChildElements[0] as Word.Text;

            Assert.IsNotNull(text);
            Assert.AreEqual(0, text.ChildElements.Count);
            Assert.AreEqual(content, text.InnerText);
        }
예제 #27
0
        private void SetCellText(TableCell cell, string text, bool bold)
        {
            ParagraphProperties parProperties = new ParagraphProperties();

            parProperties.Justification     = new Justification();
            parProperties.Justification.Val = JustificationValues.Center;
            Paragraph paragraph = new Paragraph();

            paragraph.AppendChild(parProperties);
            var run = new Run(new Text(text));

            run.RunProperties              = new RunProperties();
            run.RunProperties.FontSize     = new FontSize();
            run.RunProperties.FontSize.Val = new StringValue("28");
            if (bold)
            {
                run.RunProperties.Bold = new Bold();
            }
            paragraph.AppendChild(run);
            cell.AppendChild(paragraph);
        }
예제 #28
0
        public void W054_Load_Save_Strict()
        {
            var fileInfo = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, Guid.NewGuid().ToString() + ".docx"));
            var orig = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, "Strict01.docx"));
            File.Copy(orig.FullName, fileInfo.FullName);

            using (WordprocessingDocument doc =
                WordprocessingDocument.Open(fileInfo.FullName, true))
            {
                W.Body body = doc.MainDocumentPart.Document.Body;
                W.Paragraph para = body.Elements<W.Paragraph>().First();
                var newPara = new W.Paragraph(
                    new W.Run(
                        new W.Text("Test")));
                para.InsertBeforeSelf(newPara);
                OpenXmlValidator v = new OpenXmlValidator(FileFormatVersions.Office2013);
                var errs = v.Validate(doc);
            }
            if (TestUtil.DeleteTempFiles)
                fileInfo.Delete();
        }
예제 #29
0
        public WordDocument(string filename)
        {
            _filename = filename;
            using (
                WordprocessingDocument wordDoc = WordprocessingDocument.Create(_filename,
                                                                               WordprocessingDocumentType.Document))
            {
                _mainPart          = wordDoc.AddMainDocumentPart();
                _mainPart.Document = new Document();
                _body = _mainPart.Document.AppendChild(new Body());

                DateTime saveNow = DateTime.Now;

                Paragraph     para          = _body.AppendChild(new Paragraph());
                Run           run           = para.AppendChild(new Run());
                RunProperties runProperties = getHeading1(run);
                run.AppendChild(new Text("Decision Report [" + saveNow + "]"));
                //_body.Append(new Paragraph(new Run(new Text("Decision Report [" + saveNow + "]"))));
                _body.AppendChild(new Paragraph());
            }
        }
예제 #30
0
        public static void Render(this Page page, Models.Document document, OpenXmlElement wdDoc, ContextModel context, MainDocumentPart mainDocumentPart, IFormatProvider formatProvider)
        {
            if (!string.IsNullOrWhiteSpace(page.ShowKey) && context.ExistItem <BooleanModel>(page.ShowKey) && !context.GetItem <BooleanModel>(page.ShowKey).Value)
            {
                return;
            }

            // add page content
            ((BaseElement)page).Render(document, wdDoc, context, mainDocumentPart, formatProvider);

            // add section to manage orientation. Last section is at the end of document
            var pageSize = new PageSize()
            {
                Orient = page.PageOrientation.ToOOxml(),
                Width  = UInt32Value.FromUInt32(page.PageOrientation == PageOrientationValues.Landscape ? (uint)16839 : 11907),
                Height = UInt32Value.FromUInt32(page.PageOrientation == PageOrientationValues.Landscape ? (uint)11907 : 16839)
            };
            var sectionProps = new SectionProperties(pageSize);

            // document margins
            if (page.Margin != null)
            {
                var pageMargins = new PageMargin()
                {
                    Left   = page.Margin.Left,
                    Top    = page.Margin.Top,
                    Right  = page.Margin.Right,
                    Bottom = page.Margin.Bottom,
                    Footer = page.Margin.Footer,
                    Header = page.Margin.Header
                };
                sectionProps.AppendChild(pageMargins);
            }
            var p   = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
            var ppr = new ParagraphProperties();

            p.AppendChild(ppr);
            ppr.AppendChild(sectionProps);
            wdDoc.AppendChild(p);
        }
        private WordParagraph GetParagraphHeader()
        {
            WordParagraph       p  = new WordParagraph();
            ParagraphProperties pp = new ParagraphProperties(
                new Justification()
            {
                Val = JustificationValues.Left
            },
                new Indentation()
            {
                Left = (renderData.RenderSettings.TabValue * Depth).ToString()
            });

            p.Append(pp);

            Run           run           = new Run();
            RunProperties runProperties = new RunProperties(new RunFonts()
            {
                HighAnsi = renderData.RenderSettings.FontFamily, Ascii = renderData.RenderSettings.FontFamily
            })
            {
                Color = new Color()
                {
                    Val = renderData.RenderSettings.DefaultColor
                },
                FontSize = new FontSize()
                {
                    Val = renderData.RenderSettings.DefaultTextSize
                },
                Bold = new Bold()
            };

            Text text = new Text(Name);

            run.Append(runProperties);
            run.Append(text);
            p.Append(run);

            return(p);
        }
        public OpenXmlElement SectionTitlePart(int sectionNumber)
        {
            var paragraph = new Paragraph();

            var run = new Run();

            var runProperties = new RunProperties();
            var bold          = new Bold();

            bold.Val = OnOffValue.FromBoolean(true);
            runProperties.Append(bold);

            run.Append(runProperties);

            var text = new Text($"( {sectionNumber} ) {Section}");

            run.Append(text);

            paragraph.Append(run);

            return(paragraph);
        }
예제 #33
0
        private Paragraph ExamTitleHeader()
        {
            var paragraphWithExamTitle = new Paragraph();

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

            paragraphProperties.Append(justification);

            run.Append(new Text($"Exam: {exam.Subject}"));
            run.Append(new Break());
            run.Append(new Text($"Teacher: {exam.Teacher}"));

            paragraphWithExamTitle.Append(paragraphProperties);
            paragraphWithExamTitle.Append(run);

            return(paragraphWithExamTitle);
        }
예제 #34
0
        //:::::WORD DOCUMENT PROCESSING PART:::::
        public static void AddToTable(String fileName, String tableName, int elemNo, String txt, int elemRow = 0)
        {
            List <WordP.Table> tables = null;

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileName, true))
            {
                tables = new List <WordP.Table>(wordDoc.MainDocumentPart.Document.Body.Elements <WordP.Table>());
                tables.ForEach(table =>
                {
                    WordP.TableProperties tblProperties = table.GetFirstChild <WordP.TableProperties>();
                    if (tblProperties != null)
                    {
                        WordP.TableCaption caption = tblProperties.GetFirstChild <WordP.TableCaption>();
                        if (caption != null)
                        {
                            if (caption.Val.HasValue && caption.Val.Value.Equals(tableName))
                            {
                                WordP.TableRow row = table.Elements <WordP.TableRow>().ElementAt(elemNo);

                                // Find the third cell in the row.
                                WordP.TableCell cell = row.Elements <WordP.TableCell>().ElementAt(elemRow);

                                // Find the first paragraph in the table cell.
                                WordP.Paragraph p = cell.Elements <WordP.Paragraph>().First();

                                // Find the first run in the paragraph.
                                WordP.Run r = p.Elements <WordP.Run>().First();

                                // Set the text for the run.
                                WordP.Text t = r.Elements <WordP.Text>().First();
                                t.Text       = txt;

                                // you have got your table. process the rest.
                            }
                        }
                    }
                });
            }
        }
예제 #35
0
        private WordParagraph GetSectionHeadParagraph()
        {
            WordParagraph       p  = new WordParagraph();
            ParagraphProperties pp = new ParagraphProperties(new Justification()
            {
                Val = JustificationValues.Center
            });

            p.Append(pp);

            Run           run           = new Run();
            RunProperties runProperties = new RunProperties(new RunFonts()
            {
                HighAnsi = renderData.RenderSettings.FontFamily,
                Ascii    = renderData.RenderSettings.FontFamily
            })
            {
                Color = new Color()
                {
                    Val = renderData.RenderSettings.DefaultColor
                },
                FontSize = new FontSize()
                {
                    Val = renderData.RenderSettings.DefaultTextSize
                },
                Caps = new Caps(),
                Bold = new Bold()
            };

            run.Append(runProperties);

            Text text = new Text(Name);

            run.Append(text);
            p.Append(run);

            return(p);
        }
예제 #36
0
        public void W015_InsertBeforeSelf()
        {
            using (var stream = GetStream(TestFiles.Document))
                using (var doc = WordprocessingDocument.Open(stream, false))
                {
                    var mdp     = doc.MainDocumentPart;
                    var newPara = new W.Paragraph(
                        new W.Run(
                            new W.Text("Hello")));
                    var firstPara = mdp.Document.Body.Elements <W.Paragraph>().FirstOrDefault();

                    firstPara.InsertBeforeSelf(newPara);

                    var v = new OpenXmlValidator(FileFormatVersions.Office2013);

                    Assert.Collection(
                        v.Validate(doc),
                        e =>
                    {
                        Assert.Equal("Sem_UniqueAttributeValue", e.Id);
                    });
                }
        }
예제 #37
0
        public void AddParagraph()
        {
            using (var doc = WordprocessingDocument.Open("Templates\\CKEmptyTemplate.docx", true, new OpenSettings { MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2010) }))
            {
                var text = new Text("Perec");
                var run = new Run();
                run.RunProperties = new RunProperties();
                run.RunProperties.RunStyle = new RunStyle { Val = "TitleChar" };
                run.Append(text);
                var paragraph = new Paragraph(run);
                //paragraph.ParagraphProperties = new ParagraphProperties {ParagraphStyleId = new ParagraphStyleId { Val = "Title" }};

                var text2 = new Text("Alma");
                var run2 = new Run();
                run2.Append(text2);
                run2.RunProperties = new RunProperties();
                run2.RunProperties.RunStyle = new RunStyle { Val = "Normal" };
                paragraph.Append(run2);

                doc.MainDocumentPart.Document.Body.AppendChild<Paragraph>(paragraph);
                doc.MainDocumentPart.Document.Save();
            }
        }
        public static DocumentFormat.OpenXml.OpenXmlElement[] GetFormattedSection(MultiColumnSection section)
        {
            List<DocumentFormat.OpenXml.OpenXmlElement> formattedSection = new List<DocumentFormat.OpenXml.OpenXmlElement>();
            Element[] elements = section.SubElements;

            foreach (var element in elements)
            {
                formattedSection.AddRange(ElementFactory.GetElement(element));
            }

            Word.Columns cols = new Word.Columns()
            {
                ColumnCount = (Int16Value)section.NumberOfColumns
            };

            Word.SectionProperties secProps = new Word.SectionProperties(cols);
            Word.ParagraphProperties paraProp = new Word.ParagraphProperties(secProps);
            Word.Paragraph para = new Word.Paragraph(paraProp);

            formattedSection.Add(para);

            return formattedSection.ToArray();
        }
        public static DocumentFormat.OpenXml.OpenXmlElement[] GetFormattedSection(Section section)
        {
            List<DocumentFormat.OpenXml.OpenXmlElement> formattedSection = new List<DocumentFormat.OpenXml.OpenXmlElement>();
            Element[] elements = section.SubElements;

            foreach (var element in elements)
            {
                if (section.CanContain(element.GetElementType())) formattedSection.AddRange(ElementFactory.GetElement(element));
                else throw new InvalidSubFeatureException( section.GetElementType().ToString(), element.GetElementType().ToString() );
            }

            Word.Columns cols = new Word.Columns()
            {
                ColumnCount = (Int16Value)1
            };

            Word.SectionProperties secProps = new Word.SectionProperties(cols);
            Word.ParagraphProperties paraProp = new Word.ParagraphProperties(secProps);
            Word.Paragraph para = new Word.Paragraph(paraProp);

            formattedSection.Add(para);

            return formattedSection.ToArray();
        }
        public void ProcessWordDocument(string docFilePath)
        {
            tableIndex = 1;
            mathIndex = 1;
            imageIndex = 1;
            textIndex = 1;
            using (WordprocessingDocument doc = WordprocessingDocument.Open(docFilePath, false))
            {
                foreach (var table in doc.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Table>())
                {
                    int trows = table.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableRow>().Count();
                    int tcols = table.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableRow>().First().Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().Count();
                    WordTable wordTable = new WordTable(trows, tcols);
                    //create a table class and add the text from the rows and cells
                    int row = 0, cell = 0;
                    foreach (var tableRow in table.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableRow>())
                    {
                        foreach (var tableCell in tableRow.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>())
                        {
                            string text = tableCell.InnerText;
                            wordTable.AddText(row, cell, text);
                            cell++;
                            //save the cell into a table class for later processing with row info
                        }
                        cell = 0;
                        row++;
                    }
                    DocumentFormat.OpenXml.Wordprocessing.Paragraph para = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
                    Run run = para.AppendChild(new Run());
                    string IDplaceholder = "%Table-&" + tableIndex;
                    run.AppendChild(new Text(IDplaceholder));
                    table.Parent.ReplaceChild(para, table);
                    //table.Remove();
                    tableIndex++;
                    //store the table
                    TableList.Add(IDplaceholder, wordTable);
                }
                foreach (var formula in doc.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Math.OfficeMath>())
                {
                    string wordDocXml = formula.OuterXml;
                    XslCompiledTransform xslTransform = new XslCompiledTransform();
                    xslTransform.Load(officeMathMLSchemaFilePath);
                    string mmlFormula = null;

                    using (TextReader tr = new StringReader(wordDocXml))
                    {
                        // Load the xml of your main document part.
                        using (XmlReader reader = XmlReader.Create(tr))
                        {
                            XmlWriterSettings settings = xslTransform.OutputSettings.Clone();

                            // Configure xml writer to omit xml declaration.
                            settings.ConformanceLevel = ConformanceLevel.Fragment;
                            settings.OmitXmlDeclaration = true;

                            using (MemoryStream ms = new MemoryStream())
                            {
                                XmlWriter xw = XmlWriter.Create(ms, settings);

                                // Transform our OfficeMathML to MathML.
                                xslTransform.Transform(reader, xw);
                                ms.Seek(0, SeekOrigin.Begin);
                                using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
                                {
                                    mmlFormula = sr.ReadToEnd();
                                }
                            }
                        }
                        DocumentFormat.OpenXml.Wordprocessing.Paragraph para = formula.Parent.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
                        Run run = para.AppendChild(new Run());
                        string IDplaceholder = "%Math-&" + mathIndex;
                        run.AppendChild(new Text(IDplaceholder));
                        mathIndex++;
                        formula.Remove();
                        if (mmlFormula != null)
                        {
                            MathList.Add(IDplaceholder, mmlFormula);
                        }

                    }
                }
                foreach (var graphic in doc.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Drawing.Graphic>())
                {
                    DocumentFormat.OpenXml.Drawing.Blip blip = graphic.FirstChild.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().First();
                    string imageId = blip.Embed.Value;
                    ImagePart imagePart = (ImagePart)doc.MainDocumentPart.GetPartById(imageId);
                    var uri = imagePart.Uri;
                    var filename = uri.ToString().Split('/').Last();
                    var stream = doc.Package.GetPart(uri).GetStream();
                    Bitmap b = new Bitmap(stream);
                    string imagePath = TempImageFolder + filename;
                    b.Save(imagePath);
                    DocumentFormat.OpenXml.Wordprocessing.Paragraph para = graphic.Parent.Parent.Parent.Parent.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
                    Run run = para.AppendChild(new Run());
                    string IDplaceholder = "%Image-&" + imageIndex;
                    run.AppendChild(new Text(IDplaceholder));
                    imageIndex++;
                    ImageList.Add(IDplaceholder, imagePath);
                }
                try
                {
                    foreach (var video in doc.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Drawing.VideoFromFile>())
                    {
                        string localName = video.LocalName;
                        string innerXml = video.InnerXml;
                    }
                    foreach (var video in doc.MainDocumentPart.EmbeddedObjectParts)
                    {
                        string vct = video.ContentType;
                    }
                } catch
                {

                }
                foreach (var element in doc.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>())
                {
                    try
                    {
                        var psID = element.ParagraphProperties.ParagraphStyleId;
                        string type = null;
                        switch (psID.Val.ToString().ToLowerInvariant())
                        {
                            //for each case save the inner text of the paragraph and remove it
                            case "heading1": { type = "h1-"; break; }
                            case "heading2": { type = "h2-"; break; }
                            case "heading3": { type = "h3-"; break; }
                            case "heading4": { type = "h4-"; break; }
                            case "heading5": { type = "h5-"; break; }
                            case "title": { type = "title-"; break; }
                            case "subtitle": { type = "subtitle-"; break; }
                            default: break;
                        }
                        if (type != null)
                        {
                            string id = "%" + type + "&" + textIndex;
                            PlainTextList.Add(id, element.InnerText);
                            textIndex++;
                            element.RemoveAllChildren();
                            DocumentFormat.OpenXml.Wordprocessing.Paragraph para = element.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
                            Run run = para.AppendChild(new Run());
                            run.AppendChild(new Text(id));
                        }
                    }
                    catch
                    { //do nothing 
                    }
                }

                PlaceholderIDList = ExtractTextAndCreatePlaceholderList(doc);
                if (textBuilder.Length > 0)
                {
                    string s2 = AddTextToTextList();
                    if (s2 != null)
                        PlaceholderIDList.Add(s2);
                }
            }
        }
        public void AddTextToWord(WordprocessingDocument doc, string text, bool bold, bool italic, bool underline, int heading, int slideNumber)
        {
            MainDocumentPart mainPart = doc.MainDocumentPart;
            WordDoc.Body body = mainPart.Document.Body;
            WordDoc.Paragraph para = new WordDoc.Paragraph();
            foreach (WordDoc.Paragraph p in body.Elements<WordDoc.Paragraph>())
            {
                para = p;
            }
            if (heading != 0)
            {
                para = body.AppendChild(new WordDoc.Paragraph());
                para.ParagraphProperties = new WordDoc.ParagraphProperties(new WordDoc.ParagraphStyleId() { Val = "Heading" + heading.ToString() });
                bold = false;
                italic = false;
                underline = false;
                WordDoc.BookmarkStart bs = new WordDoc.BookmarkStart();
                bs.Id = slideNumber.ToString();
                bs.Name = text;
                bs = para.AppendChild(bs);
            }
            else
            {
                if (para.ParagraphProperties != null)
                {
                    if (para.ParagraphProperties.ParagraphStyleId != null)
                    {
                        if (para.ParagraphProperties.ParagraphStyleId.Val == "Heading1" ||
                          para.ParagraphProperties.ParagraphStyleId.Val == "Heading2" ||
                          para.ParagraphProperties.ParagraphStyleId.Val == "Heading3")
                        {
                            para = body.AppendChild(new WordDoc.Paragraph());
                        }
                    }
                }
            }

            string[] t1 = text.Split('\n');
            for (int j = 0; j < t1.Length; j++)
            {

                WordDoc.Run run = para.AppendChild(new WordDoc.Run());
                WordDoc.RunProperties rp = run.AppendChild(new WordDoc.RunProperties());
                if (bold)
                {
                    WordDoc.Bold b = rp.AppendChild(new WordDoc.Bold());
                }
                if (italic)
                {
                    WordDoc.Italic i = rp.AppendChild(new WordDoc.Italic());
                }
                if (underline)
                {
                    WordDoc.Underline u = new WordDoc.Underline()
                    {
                        Val = WordDoc.UnderlineValues.Single
                    };
                    rp.AppendChild(u);
                }
                WordDoc.Text t = new WordDoc.Text()
                {
                    Text = t1[j],
                    Space = SpaceProcessingModeValues.Preserve
                };
                run.AppendChild(t);
                if (j != t1.Length - 1)
                    run.AppendChild(new WordDoc.Break());

            }
            WordDoc.BookmarkEnd be = new WordDoc.BookmarkEnd();
            be.Id = slideNumber.ToString();
            be = para.AppendChild(be);
        }
예제 #42
0
        public static void AddImage(this WP.Body body, MainDocumentPart mainpart, string filename, string SigId)
        {

            byte[] imageFileBytes;
            Bitmap image = null;

            // Open a stream on the image file and read it's contents.
            using (FileStream fsImageFile = System.IO.File.OpenRead(filename))
            {
                imageFileBytes = new byte[fsImageFile.Length];
                fsImageFile.Read(imageFileBytes, 0, imageFileBytes.Length);
                image = new Bitmap(fsImageFile);
            }
            long imageWidthEMU = (long)((image.Width / image.HorizontalResolution) * 914400L);
            long imageHeightEMU = (long)((image.Height / image.VerticalResolution) * 914400L);

            // add this is not already there
            try
            {
                if (mainpart.GetPartById(SigId) == null)
                {
                    var imagePart = mainpart.AddNewPart<ImagePart>("image/jpeg", SigId);

                    using (BinaryWriter writer = new BinaryWriter(imagePart.GetStream()))
                    {
                        writer.Write(imageFileBytes);
                        writer.Flush();
                    }
                }
            }
            catch // thrown if not found
            {
                var imagePart = mainpart.AddNewPart<ImagePart>("image/jpeg", SigId);

                using (BinaryWriter writer = new BinaryWriter(imagePart.GetStream()))
                {
                    writer.Write(imageFileBytes);
                    writer.Flush();
                }

            }
            WP.Paragraph para =
            new WP.Paragraph(
              new WP.Run(
                new WP.Drawing(
                  new wp.Inline(

                    new wp.Extent()
                    {
                        Cx = imageWidthEMU,
                        Cy = imageHeightEMU
                    },

                    new wp.EffectExtent()
                    {
                        LeftEdge = 19050L,
                        TopEdge = 0L,
                        RightEdge = 9525L,
                        BottomEdge = 0L
                    },

                    new wp.DocProperties()
                    {
                        Id = (UInt32Value)1U,
                        Name = "Inline Text Wrapping Picture",
                        Description = GraphicDataUri
                    },

                    new wp.NonVisualGraphicFrameDrawingProperties(
                      new a.GraphicFrameLocks() { NoChangeAspect = true }),

                    new a.Graphic(
                      new a.GraphicData(
                        new pic.Picture(

                          new pic.NonVisualPictureProperties(
                            new pic.NonVisualDrawingProperties()
                            {
                                Id = (UInt32Value)0U,
                                Name = filename
                            },
                            new pic.NonVisualPictureDrawingProperties()),

                          new pic.BlipFill(
                            new a.Blip() { Embed = SigId },
                            new a.Stretch(
                              new a.FillRectangle())),

                          new pic.ShapeProperties(
                            new a.Transform2D(
                              new a.Offset() { X = 0L, Y = 0L },
                              new a.Extents()
                              {
                                  Cx = imageWidthEMU,
                                  Cy = imageHeightEMU
                              }),

                            new a.PresetGeometry(
                              new a.AdjustValueList()
                            ) { Preset = a.ShapeTypeValues.Rectangle }))
                      ) { Uri = GraphicDataUri })
                  )
                  {
                      DistanceFromTop = (UInt32Value)0U,
                      DistanceFromBottom = (UInt32Value)0U,
                      DistanceFromLeft = (UInt32Value)0U,
                      DistanceFromRight = (UInt32Value)0U
                  }))

            );

            body.Append(para);
        }
        private void InsertPageBreak(WordprocessingDocument wordprocessingDocument)
        {
            MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
            WordDoc.Body body = mainPart.Document.Body;
            WordDoc.Paragraph para = new WordDoc.Paragraph();
            para = body.AppendChild(new WordDoc.Paragraph());

            WordDoc.Run run = para.AppendChild(new WordDoc.Run(
                new WordDoc.Break() { Type = WordDoc.BreakValues.Page }
                ));
        }
 Word.TableRow CreateRow(ArrayList cellText)
 {
     Word.TableRow tr = new Word.TableRow();
     // Create cells with simple text.
     foreach (string s in cellText)
     {
         Word.TableCell tc = new Word.TableCell();
         Word.Paragraph p = new Word.Paragraph();
         Word.Run r = new Word.Run();
         Word.Text t = new Word.Text(s);
         r.AppendChild(t);
         p.AppendChild(r);
         tc.AppendChild(p);
         tr.AppendChild(tc);
     }
     return tr;
 }
예제 #45
0
        private void setupHAAADerailersTableTemplate()
        {
            String templateDoc = _projecto.Template_Mnemonica;

            String filename = rootPath + "docTemplates\\" + templateDoc + "_DERAILER_HAAA.docx";

            using (WordprocessingDocument tempDoc = WordprocessingDocument.Open(filename, true))
            {

                tempTable = (wp.Table)tempDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(0).Clone();

                // selecciona as linhas
                tempRowHeader = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(0).Clone();
                tempRowSeparador = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(1).Clone();
                tempRowHeader2 = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(2).Clone();
                tempRowImpar = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(3).Clone();
                tempRowPar = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(4).Clone();

                // selecciona os símbolos
                // Target
                // Neutro
                // A Desenvolver
                // linhas 3,4 e 5 Coluna 1

                symbDelevop = tempRowImpar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar;
                tempRowImpar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First().Remove();
                symbNeutral = tempRowPar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar;
                tempRowPar.Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First().Remove();

                symbTarget = tempTable.Elements<wp.TableRow>().ElementAt(5).Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar;
                tempTable.Elements<wp.TableRow>().ElementAt(5).Elements<wp.TableCell>().ElementAt(3).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First().Remove();

                // limpa a tabela
                tempTable.Elements<wp.TableRow>().ElementAt(0).Remove();
                tempTable.Elements<wp.TableRow>().ElementAt(0).Remove();
                tempTable.Elements<wp.TableRow>().ElementAt(0).Remove();
                tempTable.Elements<wp.TableRow>().ElementAt(0).Remove();
                tempTable.Elements<wp.TableRow>().ElementAt(0).Remove();
                tempTable.Elements<wp.TableRow>().ElementAt(0).Remove();

                tempParagraph = tempDoc.MainDocumentPart.Document.Body.Descendants<wp.Paragraph>().ElementAt(0).Clone() as wp.Paragraph;

            }
        }
예제 #46
0
        private void insertAARank(wp.Paragraph par)
        {
            List<ReportRow> results;
            //MediasCompetencia medias;
            wp.Paragraph tempPar = new wp.Paragraph(); ;
            wp.TableRow tRow;
            setupAARankTable();
            wp.Table novaTabela = tempTable.Clone() as wp.Table;

            clearParagraphText(par);

            results = repCalcs.getRankingSELF();

            foreach (ReportRow rr in results)
            {
                tRow = tempRowImpar.Clone() as wp.TableRow;
                setText(rr.dados[0], tRow.Elements<wp.TableCell>().ElementAt(0));
                setText(rr.dados[2], tRow.Elements<wp.TableCell>().ElementAt(1));
                setText(rr.dados[1], tRow.Elements<wp.TableCell>().ElementAt(2));
                novaTabela.Append(tRow);
            }
            par.RemoveAllChildren<wp.Text>();
            par.Append(novaTabela);
        }
        void ImportSmartArtFromPowerPoint(MainDocumentPart mainPart, Word.SdtElement sdt, SPFile filename)
        {
            string docLayoutPartId = "";
            string docDataPartId = "";
            string docColorsPartId = "";
            string docStylePartId = "";

            byte[] byteArray = filename.OpenBinary();

            using (MemoryStream mem = new MemoryStream())
            {
                mem.Write(byteArray, 0, (int)byteArray.Length);

                using (PresentationDocument myPres = PresentationDocument.Open(mem, true))
                {
                    PresentationPart presPart = myPres.PresentationPart;
                    // Get the slide that contains the SmartArt graphic.
                    SlidePart slide = (SlidePart)presPart.GetPartById("rId3");
                    // Get all the appropriate parts associated with the SmartArt.
                    DiagramLayoutDefinitionPart layoutPart =
                       slide.DiagramLayoutDefinitionParts.First();
                    DiagramDataPart dataPart = slide.DiagramDataParts.First();
                    DiagramColorsPart colorsPart = slide.DiagramColorsParts.First();
                    DiagramStylePart stylePart = slide.DiagramStyleParts.First();

                    // Get some of the appropriate properties off the SmartArt graphic.
                    PPT.GraphicFrame graphicFrame =
                       slide.Slide.Descendants<PPT.GraphicFrame>().First();
                    PPT.NonVisualDrawingProperties drawingPr = graphicFrame
                       .Descendants<PPT.NonVisualDrawingProperties>().First();
                    Draw.Extents extents =
                       graphicFrame.Descendants<Draw.Extents>().First();

                    // Import SmartArt into the Word document.
                    // Add the SmartArt parts to the Word document.
                    DiagramLayoutDefinitionPart docLayoutPart =
                       mainPart.AddPart<DiagramLayoutDefinitionPart>(layoutPart);
                    DiagramDataPart docDataPart =
                       mainPart.AddPart<DiagramDataPart>(dataPart);
                    DiagramColorsPart docColorsPart =
                       mainPart.AddPart<DiagramColorsPart>(colorsPart);
                    DiagramStylePart docStylePart =
                       mainPart.AddPart<DiagramStylePart>(stylePart);
                    // Get all the relationship ids of the added parts.
                    docLayoutPartId = mainPart.GetIdOfPart(docLayoutPart);
                    docDataPartId = mainPart.GetIdOfPart(docDataPart);
                    docColorsPartId = mainPart.GetIdOfPart(docColorsPart);
                    docStylePartId = mainPart.GetIdOfPart(docStylePart);

                    // Use the document reflector to figure out how to add a SmartArt
                    // graphic to Word.
                    // Change attribute values based on specifics related to the SmartArt.
                    Word.Paragraph p = new Word.Paragraph(
                       new Word.Run(
                       new Word.Drawing(
                       new WP.Inline(
                       new WP.Extent() { Cx = extents.Cx, Cy = extents.Cy },
                       new WP.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
                       new WP.DocProperties() { Id = drawingPr.Id, Name = drawingPr.Name },
                       new WP.NonVisualGraphicFrameDrawingProperties(),
                       new Draw.Graphic(
                       new Draw.GraphicData(
                       new Dgm.RelationshipIds()
                       {
                           DataPart = docDataPartId,
                           LayoutPart = docLayoutPartId,
                           StylePart = docStylePartId,
                           ColorPart = docColorsPartId
                       }) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/diagram" }))
                       {
                           DistanceFromTop = (UInt32Value)0U,
                           DistanceFromBottom = (UInt32Value)0U,
                           DistanceFromLeft = (UInt32Value)0U,
                           DistanceFromRight = (UInt32Value)0U
                       })));

                    // Swap out the content control for the SmartArt.
                    OpenXmlElement parent = sdt.Parent;
                    parent.InsertAfter(p, sdt);
                    sdt.Remove();
                }
            }
        }
예제 #48
0
        private void insertAABehaveTables(Boolean auto, wp.Paragraph par)
        {
            List<ReportRow> results;
            MediasCompetencia medias;
            wp.Paragraph tempPar = new wp.Paragraph(); ;
            wp.TableRow tRow;
            setupAABehaveTableTemplate();
            int count;
            wp.Table novaTabela = tempTable.Clone() as wp.Table;

            clearParagraphText(par);

            // temos de lidar aqui com o bloco dos derailers
            foreach (FamiliaCompetencias fam in _Modelo.Familias.Values)
                foreach (Competencia comp in fam.Competencias.Values.Where(a => a.Type != "D"))
                {
                    results = repCalcs.getAvaliacaoComportamentosCriticosExtended(comp.CompetenciaID);
                    medias = repCalcs.getMediasCompetencia(comp.CompetenciaID);

                    tRow = tempRowHeader.Clone() as wp.TableRow;
                    setText(repCalcs.getCompetenciaText(comp.CompetenciaID), tRow.Elements<wp.TableCell>().ElementAt(0));

                    setText(medias.mS.ToString("0.00"), tRow.Elements<wp.TableCell>().ElementAt(1));
                    novaTabela.Append(tRow);

                    tRow = tempRowSeparador.Clone() as wp.TableRow; //separador
                    novaTabela.Append(tRow);

                    tRow = tempRowHeader2.Clone() as wp.TableRow; //segundo header
                    novaTabela.Append(tRow);

                    count = 1;
                    results.RemoveAt(0); // para retirara as legendas que aqui naão são utilizadas

                    foreach (ReportRow rr in results)
                    {
                        if (count % 2 == 0)
                        {
                            //par
                            tRow = tempRowPar.Clone() as wp.TableRow;
                        }
                        else
                        {
                            //impar
                            tRow = tempRowImpar.Clone() as wp.TableRow;
                        }

                        setText(rr.dados[0], tRow.Elements<wp.TableCell>().ElementAt(0));
                        if (rr.dados[1] == "0")
                            rr.dados[1] = "";
                        setText(rr.dados[1], tRow.Elements<wp.TableCell>().ElementAt(1));
                        if (rr.dados[6] == "-1.00")
                            rr.dados[6] = "-";
                        setText(rr.dados[6], tRow.Elements<wp.TableCell>().ElementAt(2));
                        novaTabela.Append(tRow);
                        count++;
                    }

                    // colocar um parágrafo

                    novaTabela.Append(tempParagraph.Clone() as wp.Paragraph);

                }

            par.RemoveAllChildren<wp.Text>();
            par.Append(novaTabela);
        }
예제 #49
0
        private void insertAADerailers(wp.Paragraph par)
        {
            List<ReportRow> results;
            wp.Paragraph tempPar = new wp.Paragraph(); ;
            wp.TableRow tRow;
            setupAADerailersTableTemplate();
            int count;
            wp.Table novaTabela = tempTable.Clone() as wp.Table;
            wp.SymbolChar simbolo;
            float valor;
            clearParagraphText(par);

            // temos de lidar aqui com o bloco dos derailers
            foreach (FamiliaCompetencias fam in _Modelo.Familias.Values)
                foreach (Competencia comp in fam.Competencias.Values.Where(a => a.Type == "D"))
                {
                    results = repCalcs.getAvaliacaoDerailersExtended(comp.CompetenciaID);
                    //medias = repCalcs.getMediasCompetencia(comp.CompetenciaID);

                    tRow = tempRowHeader.Clone() as wp.TableRow;
                    setText(repCalcs.getCompetenciaText(comp.CompetenciaID), tRow.Elements<wp.TableCell>().ElementAt(0));

                    //setText(medias.mS.ToString("0.00"), tRow.Elements<wp.TableCell>().ElementAt(1));
                    novaTabela.Append(tRow);

                    tRow = tempRowSeparador.Clone() as wp.TableRow; //separador
                    novaTabela.Append(tRow);

                    tRow = tempRowHeader2.Clone() as wp.TableRow; //segundo header
                    novaTabela.Append(tRow);

                    count = 1;
                    results.RemoveAt(0); // para retirara as legendas que aqui não são utilizadas

                    foreach (ReportRow rr in results)
                    {
                        if (count % 2 == 0)
                        {
                            //par
                            tRow = tempRowPar.Clone() as wp.TableRow;
                        }
                        else
                        {
                            //impar
                            tRow = tempRowImpar.Clone() as wp.TableRow;
                        }

                        setText(rr.dados[0], tRow.Elements<wp.TableCell>().ElementAt(0));
                        valor = float.Parse(rr.dados[6]);

                        if (valor <= 2)
                        {
                            // on target
                            simbolo = symbTarget.Clone() as wp.SymbolChar;
                        }
                        else if (valor >= 4)
                        {
                            // a desenvolver
                            simbolo = symbDelevop.Clone() as wp.SymbolChar;
                        }
                        else
                        {
                            // neutro
                            simbolo = symbNeutral.Clone() as wp.SymbolChar;
                        }

                        tRow.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().AppendChild<wp.SymbolChar>(simbolo);

                        if (rr.dados[6] == "-1.00")
                            rr.dados[6] = "-";
                        setText(rr.dados[6], tRow.Elements<wp.TableCell>().ElementAt(2));
                        novaTabela.Append(tRow);
                        count++;
                    }

                    // colocar um parágrafo

                    novaTabela.Append(tempParagraph.Clone() as wp.Paragraph);

                }

            par.RemoveAllChildren<wp.Text>();
            par.Append(novaTabela);
        }
예제 #50
0
        private void setupRankingTables()
        {
            rankingTables = true;
            String templateDoc = _projecto.Template_Mnemonica;

            String filename = rootPath + "docTemplates\\" + templateDoc + "_RANKING.docx";

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filename, true))
            {
                tableRankS = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(0).Clone();
                tableRankT = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(1).Clone();
                tableRankB = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(2).Clone();
                tableRankC = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(3).Clone();
                tableRankP = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(4).Clone();
                tableRankO = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(5).Clone();

                trRankRowImpar = (wp.TableRow)tableRankS.Elements<wp.TableRow>().ElementAt(1);
                trRankRowPar = (wp.TableRow)tableRankS.Elements<wp.TableRow>().ElementAt(2);

                tableRankS.Elements<wp.TableRow>().ElementAt(1).Remove();
                tableRankS.Elements<wp.TableRow>().ElementAt(1).Remove();

                parHeadingParS = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(0);
                parHeadingParT = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(1);
                parHeadingParB = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(2);
                parHeadingParC = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(3);
                parHeadingParP = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(4);
                parHeadingParO = (wp.Paragraph)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Paragraph>().ElementAt(5);

            }
        }
예제 #51
0
        private void setupHARankTable()
        {
            String templateDoc = _projecto.Template_Mnemonica;

            String filename = rootPath + "docTemplates\\" + templateDoc + "_RANK_HA.docx";

            using (WordprocessingDocument tempDoc = WordprocessingDocument.Open(filename, true))
            {

                tempTable = (wp.Table)tempDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(0).Clone();

                tempRowHeader = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(0).Clone();
                tempRowImpar = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(1).Clone();

                tempTable.Elements<wp.TableRow>().ElementAt(1).Remove();

                tempParagraph = tempDoc.MainDocumentPart.Document.Body.Descendants<wp.Paragraph>().ElementAt(0).Clone() as wp.Paragraph;

            }
        }
예제 #52
0
        private void setupHABehaveTableTemplate()
        {
            String templateDoc = _projecto.Template_Mnemonica;

            String filename = rootPath + "docTemplates\\" + templateDoc + "_BEHAVE_HA.docx";

            using (WordprocessingDocument tempDoc = WordprocessingDocument.Open(filename, true))
            {

                tempTable = (wp.Table)tempDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(0).Clone();

                tempRowHeader = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(0).Clone();
                tempRowHeader2 = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(1).Clone();
                tempRowImpar = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(2).Clone();
                tempRowPar = (wp.TableRow)tempTable.Elements<wp.TableRow>().ElementAt(3).Clone();

                symbUp = tempRowImpar.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar;
                symbH = tempRowPar.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar;
                symbDw = tempTable.Elements<wp.TableRow>().ElementAt(4).Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.SymbolChar>().First() as wp.SymbolChar;

                tempTable.Elements<wp.TableRow>().ElementAt(0).Remove();
                tempTable.Elements<wp.TableRow>().ElementAt(0).Remove();
                tempTable.Elements<wp.TableRow>().ElementAt(0).Remove();
                tempTable.Elements<wp.TableRow>().ElementAt(0).Remove();
                tempTable.Elements<wp.TableRow>().ElementAt(0).Remove();

                tempParagraph = tempDoc.MainDocumentPart.Document.Body.Descendants<wp.Paragraph>().ElementAt(0).Clone() as wp.Paragraph;

            }
        }
예제 #53
0
        public void HyperlinkRelationshipTest()
        {
            using (var stream = new System.IO.MemoryStream(TestFileStreams.May_12_04, false))
            {
                using (WordprocessingDocument testDocument = WordprocessingDocument.Open(stream, false))
                {
                    OpenXmlValidator validator = new OpenXmlValidator();
                    var errors = validator.Validate(testDocument);
                    Assert.Equal(0, errors.Count());

                    var mainPart = testDocument.MainDocumentPart;

                    Assert.Equal(0, mainPart.ExternalRelationships.Count());
                    Assert.Equal(71, mainPart.HyperlinkRelationships.Count());

                    var rid15 = mainPart.GetReferenceRelationship("rId15");
                    Assert.Equal("rId15", rid15.Id);
                    Assert.Equal(new System.Uri("#_THIS_WEEK_IN", System.UriKind.Relative), rid15.Uri);
                    Assert.False(rid15.IsExternal);

                    var rid18 = mainPart.GetReferenceRelationship("rId18");
                    Assert.Equal("rId18", rid18.Id);
                    Assert.Equal(new System.Uri("http://www.iaswresearch.org/"), rid18.Uri);
                    Assert.True(rid18.IsExternal);
                }
            }

            using (System.IO.Stream stream = new System.IO.MemoryStream())
            {
                using (var testDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document))
                {
                    var mainPart = testDocument.AddMainDocumentPart();
                    var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Body());
                    mainPart.Document = new Document(new Body(paragraph));
                    mainPart.Document.Save();

                    var newUri = new System.Uri("#New", System.UriKind.Relative);
                    var ridnew = mainPart.AddHyperlinkRelationship(newUri, false);
                    var newRel = mainPart.PackagePart.GetRelationship(ridnew.Id);
                    Assert.Equal(System.IO.Packaging.TargetMode.Internal, newRel.TargetMode);
                    Assert.Equal(ridnew.Id, newRel.Id);
                    Assert.Equal(newUri, newRel.TargetUri);
                    Assert.Equal(HyperlinkRelationship.RelationshipTypeConst, newRel.RelationshipType);

                    mainPart.DeleteReferenceRelationship(ridnew);
                    Assert.Equal(0, mainPart.HyperlinkRelationships.Count());

                    newUri = new System.Uri("http://microsoft.com", System.UriKind.Absolute);
                    ridnew = mainPart.AddHyperlinkRelationship(newUri, true, ridnew.Id);
                    newRel = mainPart.PackagePart.GetRelationship(ridnew.Id);
                    Assert.Equal(System.IO.Packaging.TargetMode.External, newRel.TargetMode);
                    Assert.Equal(ridnew.Id, newRel.Id);
                    Assert.Equal(newUri, newRel.TargetUri);
                    Assert.Equal(HyperlinkRelationship.RelationshipTypeConst, newRel.RelationshipType);

                }

                // Test the OpenXmlPartContainer.AddSubPartFromOtherPackage().
                // The method should import all hyperlink relationships.
                stream.Seek(0, System.IO.SeekOrigin.Begin);
                using (var testDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document))
                {
                    using (var sourcestream = new System.IO.MemoryStream(TestFileStreams.May_12_04, false))
                    {
                        using (WordprocessingDocument sourceDocument = WordprocessingDocument.Open(sourcestream, false))
                        {
                            var parts = new System.Collections.Generic.Dictionary<OpenXmlPart, bool>();
                            sourceDocument.MainDocumentPart.FindAllReachableParts(parts);
                            var partCounts = parts.Count;

                            var hyperlinksBefore = sourceDocument.MainDocumentPart.HyperlinkRelationships.ToArray();
                            var externalRelsBefore = sourceDocument.MainDocumentPart.ExternalRelationships.ToArray();

                            testDocument.AddPart(sourceDocument.MainDocumentPart);
                            parts.Clear();
                            testDocument.MainDocumentPart.FindAllReachableParts(parts);

                            // all parts under the main document part should be imported.
                            Assert.Equal(partCounts, parts.Count);

                            var hyperlinksAfter = testDocument.MainDocumentPart.HyperlinkRelationships.ToArray();
                            var externalRelsAfter = testDocument.MainDocumentPart.ExternalRelationships.ToArray();

                            // all hyperlink relationships should be imported.
                            Assert.Equal(hyperlinksBefore.Length, hyperlinksAfter.Length);
                            for (int i = 0; i < hyperlinksBefore.Length; i++)
                            {
                                Assert.Equal(hyperlinksBefore[i].Id, hyperlinksAfter[i].Id);
                                Assert.Equal(hyperlinksBefore[i].IsExternal, hyperlinksAfter[i].IsExternal);
                                Assert.Equal(hyperlinksBefore[i].Uri, hyperlinksAfter[i].Uri);
                            }

                            // all external relationships should be improted.
                            Assert.Equal(externalRelsBefore.Length, externalRelsAfter.Length);
                        }
                    }
                }
            }
        }
예제 #54
0
        private String insertChart(MainDocumentPart mainPart, wp.Paragraph par, String templateName, int dimx, int dimy)
        {
            String relId;
            // vai buscar o gráfico e coloca-o no local com a dimensão definida HARCODED
            wp.Paragraph chartP = new wp.Paragraph();
            wp.Run chartR = new wp.Run();
            chartP.Append(chartR);
            wp.Drawing drawing = new wp.Drawing();
            chartR.Append(drawing);

            clearParagraphText(par);

            //Open Excel spreadsheet
            using (SpreadsheetDocument mySpreadsheet = SpreadsheetDocument.Open(templateName, true))
            {
                //Get all the appropriate parts

                // assume que há apenas um gráfico por ficheiro template
                // isto deveria evoluir para um ficheiro apenas

                WorkbookPart workbookPart = mySpreadsheet.WorkbookPart;
                WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById("rId1");
                DrawingsPart drawingPart = worksheetPart.DrawingsPart;
                ChartPart chartPart = (ChartPart)drawingPart.GetPartById("rId1");

                //Clone the chart part and add it to my Word document
                ChartPart importedChartPart = mainPart.AddPart<ChartPart>(chartPart);
                relId = mainPart.GetIdOfPart(importedChartPart);

                //The frame element contains information for the chart
                ssd.GraphicFrame frame = drawingPart.WorksheetDrawing.Descendants<ssd.GraphicFrame>().First();
                string chartName = frame.NonVisualGraphicFrameProperties.NonVisualDrawingProperties.Name;

                //Clone this node so we can add it to my Word document
                Graphic clonedGraphic = (Graphic)frame.Graphic.CloneNode(true);

                // clonedGraphic.GraphicData

                ChartReference c = clonedGraphic.GraphicData.GetFirstChild<ChartReference>();
                c.Id = relId;

                //Give the chart a unique id and name
                wpd.DocProperties docPr = new wpd.DocProperties();
                docPr.Name = chartName;
                docPr.Id = GetMaxDocPrId(mainPart) + 1;

                //add the chart data to the inline drawing object
                // wpd.Inline inline = new wpd.Inline(new wpd.Extent() { Cx = 5372100, Cy = 1914525 });
                wpd.Inline inline;
                if (dimx == 0 && dimy == 0)
                    inline = new wpd.Inline();
                else
                    inline = new wpd.Inline(new wpd.Extent() { Cx = dimx, Cy = dimy });
                inline.Append(docPr, clonedGraphic);
                drawing.Append(inline);
            }

            // JUNTA O GRÁFICO
            par.Append(chartP);

            // retorna o ID do gráfico que necessita update
            return relId;
        }
        public void Build()
        {
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Create("sample.docx", WordprocessingDocumentType.Document))
            {
                wordDocument.Initialize();

                MainDocumentPart mainPart = wordDocument.MainDocumentPart;
                Body body = mainPart.Document.Body;

                var summaries = new Dictionary<Module, List<Dictionary<Tuple<Expertise, Priority>, decimal>>>();

                for (int i = 0; i < this._modules.Module.Length; i++)
                {
                    var module = this._modules.Module[i];
                    summaries.Add(module, new List<Dictionary<Tuple<Expertise, Priority>, decimal>>());

                    FormatTitle(body, module);
                    TableHelpers.AddTable(
                        wordDocument,
                        new[,]
                            {
                                {
                                    "Status", "Version", "Priority", "License"
                                },
                                { module.Status.ToString(), module.Version, module.Priority.ToString(), module.License.ToString() }
                            });

                    body.AppendChild(new Paragraph().ApplyStyle(StyleDefinitions.Heading2.Id).AppendText("Technologies"));

                    TableHelpers.AddTable(wordDocument, this.BuildTechnologyList(module.Technologies));

                    body.AppendChild(new Paragraph().ApplyStyle(StyleDefinitions.Heading2.Id).AppendText("Overview"));
                    body.AppendChild(new Paragraph()).AppendChild(new Run()).AppendChild(new Text(module.Overview));
                    body.AppendChild(new Paragraph().ApplyStyle(StyleDefinitions.Heading2.Id).AppendText("Dependencies"));
                    body.AppendChild(new Paragraph().AppendText("This module has dependencies on"));

                    foreach (var dep in module.Dependencies)
                    {
                        var paragraph = new Paragraph().AsBulletedList(0, 1);
                        paragraph.AppendText(dep);
                        body.AppendChild(paragraph);
                    }

                    body.AppendChild(new Paragraph().ApplyStyle(StyleDefinitions.Heading2.Id).AppendText("Work Remaining"));
                    TableHelpers.AddTable(
                       wordDocument,
                       this.BuildFeaturesList(module.Features));

                    var summary = new Dictionary<Tuple<Expertise, Priority>, decimal>();

                    body.AppendChild(new Paragraph().ApplyStyle(StyleDefinitions.Heading2.Id).AppendText("Pricing Matrix"));
                    TableHelpers.AddTable(
                       wordDocument,
                       this.BuildPricingMatrix(module, ref summary));

                    summaries[module].Add(summary);

                    body.AppendChild(new Paragraph().ApplyStyle(StyleDefinitions.Heading2.Id).AppendText("Totals"));
                    TableHelpers.AddTable(
                       wordDocument,
                       CalculateSummaryValues(summary, module));

                    body.AppendChild(new Paragraph(new Run(new Break { Type = BreakValues.Page })));
                }

                body.AppendChild(new Paragraph().ApplyStyle(StyleDefinitions.Heading2.Id).AppendText("Summary"));
                TableHelpers.AddTable(wordDocument, this.CalculateTotalSummaries(summaries));
            }
        }
예제 #56
0
        private void insertDetailsSkill(wp.Paragraph par, MainDocumentPart mainPart)
        {
            // na primira fase fazer sem os gráficos

            // ir buscar o template
            // cria o documento final base com base no template
            String templateDoc = _projecto.Template_Mnemonica;

            String filename = rootPath + "docTemplates\\" + templateDoc + "_SKILS_DETAILS.docx";

            wp.Table tabTitulo1;

            wp.Table tab1;
            wp.TableRow rowTab1Par;
            wp.TableRow rowTab1Impar;

            wp.Run plusSign;
            wp.Run minusSign;
            wp.Run naSign;
            wp.Run eqSign;

            wp.Table legendaTab1;
            wp.Paragraph quebraPagina;

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filename, true))
            {
                // primeira tabela do template
                tabTitulo1 = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(0).Clone();

                // primeira tabela com comportamentos
                tab1 = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(1).Clone();
                rowTab1Impar = (wp.TableRow)tab1.Elements<wp.TableRow>().ElementAt(1).Clone();
                rowTab1Par = (wp.TableRow)tab1.Elements<wp.TableRow>().ElementAt(2).Clone();
                tab1.Elements<wp.TableRow>().ElementAt(1).Remove();
                tab1.Elements<wp.TableRow>().ElementAt(1).Remove();

                // apanha os run + e - (mais e menos)
                minusSign = (wp.Run)rowTab1Impar.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Clone();
                naSign = (wp.Run)rowTab1Impar.Elements<wp.TableCell>().ElementAt(2).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Clone();
                plusSign = (wp.Run)rowTab1Par.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Clone();
                eqSign = (wp.Run)rowTab1Par.Elements<wp.TableCell>().ElementAt(2).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Clone();

                // eliminar o mais e o menos das linhas e o tracinho
                rowTab1Impar.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Remove();
                rowTab1Impar.Elements<wp.TableCell>().ElementAt(2).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Remove();
                rowTab1Par.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Remove();
                rowTab1Par.Elements<wp.TableCell>().ElementAt(2).Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Remove();

                // depois tenho algures aqui a legenda da tabela
                legendaTab1 = (wp.Table)wordDoc.MainDocumentPart.Document.Body.Elements<wp.Table>().ElementAt(2).Clone();

                //parágrafo quebra de página
                quebraPagina = new wp.Paragraph(new wp.Run(new wp.Text("")));
                quebraPagina.ParagraphProperties = new wp.ParagraphProperties();
                quebraPagina.ParagraphProperties.PageBreakBefore = new wp.PageBreakBefore();
                quebraPagina.ParagraphProperties.PageBreakBefore.Val = DocumentFormat.OpenXml.OnOffValue.FromBoolean(true);

            }
            // fim da recolha dos elementos template.
            // passamos para a inserção destes elementos para cada competência

            // eliminar o texto do marcador
            par.Elements<wp.Run>().First().Elements<wp.Text>().First().Text = "";

            wp.Paragraph p;
            wp.Run r;
            wp.Text t;
            wp.Table tab;

            wp.Table tab1Temp;

            wp.TableRow tab1r;
            wp.TableCell tab1c;

            int count = 0;

            String pergunta;
            String tempTexto;
            int contaPaginas = 1;

            foreach (FamiliaCompetencias fam in _Modelo.Familias.Values)
                foreach (Competencia comp in fam.Competencias.Values)
                {
                    // são duas páginas de detalhes por cada competência
                    // header da 1ªpágina

                    if (comp.Type == "C") continue; // é uma competência comentário
                    if (comp.Type == "D") continue; // é uma zona de derrailers

                    // Nome da competência
                    tab = (wp.Table)tabTitulo1.Clone();
                    p = tab.Elements<wp.TableRow>().ElementAt(0).Elements<wp.TableCell>().First().Elements<wp.Paragraph>().First();
                    r = p.Elements<wp.Run>().First();
                    t = r.Elements<wp.Text>().First();
                    t.Text = repCalcs.getCompetenciaText(comp.CompetenciaID);

                    par.Append(tab);// o nome da competência

                    // PREPARA AS DUAS TABELAS COM OS DETALHES
                    tab1Temp = (wp.Table)tab1.Clone();
                    // tab2Temp = (wp.Table)tab2.Clone();

                    // os valores obtidos em cada comportamento
                    List<ReportRow> dataComportamentos = repCalcs.getAvaliacaoComportamentosCriticos(comp.CompetenciaID);
                    List<ReportRow> dataComportamentosFracosFortes = repCalcs.getAvaliacaoComportamentosCriticos_FracosFortes(comp.CompetenciaID);
                    count = 0;
                    foreach (Pratica prat in comp.Praticas.Values)
                        foreach (Pergunta perg in prat.Perguntas.Values)
                        {
                            pergunta = repCalcs.getPergunta(perg.PerguntaID);
                            if (count % 2 == 0)
                            {
                                // linha par
                                tab1r = (wp.TableRow)rowTab1Par.Clone();
                                // tab2r = (wp.TableRow)rowTab2Par.Clone();
                            }
                            else
                            {
                                // linha impar
                                tab1r = (wp.TableRow)rowTab1Impar.Clone();
                                // tab2r = (wp.TableRow)rowTab2Impar.Clone();
                            }

                            tab1c = tab1r.Elements<wp.TableCell>().ElementAt(0);
                            // tab2c = tab2r.Elements<wp.TableCell>().ElementAt(0);

                            if (count + 1 < dataComportamentos.Count)
                            {
                                // introduz o texto da pergunta
                                tab1c.Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.Text>().First().Text = dataComportamentos[count + 1].dados[0];
                                // tab2c.Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.Text>().First().Text = dataComportamentos[count + 1].dados[0];
                                // introduz os valores de cada prática

                                // os mais e os menos desta linha (prática), por S;B;P;C;O
                                for (int i = 1; i < dataComportamentos[count + 1].dados.Length; i++ )
                                {
                                    tab1c = tab1r.Elements<wp.TableCell>().ElementAt(i);
                                    fillPlusMinus(tab1c, dataComportamentos[count + 1].dados[i], plusSign, minusSign, naSign, eqSign);
                                }
                            }

                            // junta às tabelas as linhas
                            tab1Temp.Append(tab1r);
                            // tab2Temp.Append(tab2r);

                            count++;
                        }

                    // INSERE A TABELA 1
                    par.Append(tab1Temp);
                    // LEGENDA 1

                    tempTexto = "";

                    //legendaTab1.Elements<wp.TableRow>().ElementAt(1).Elements<wp.TableCell>().First().Elements<wp.Paragraph>().First().Elements<wp.Run>().First().Elements<wp.Text>().First().Text = tempTexto;
                    par.Append((wp.Table)legendaTab1.Clone());

                    // QUEBRA DE PÁGINA 1
                    par.Append((wp.Paragraph)quebraPagina.Clone());

                    // um parágrafo de espaçamento para que as tabelas não colem
                    par.Append(new wp.Paragraph());

                    contaPaginas++;
                }
        }
        void ImportChartFromSpreadsheet(MainDocumentPart mainPart, Word.SdtElement sdt,
   SPFile spreadsheetFileName)
        {
            // Create a paragraph that has an inline drawing object.
            Word.Paragraph p = new Word.Paragraph();
            Word.Run r = new Word.Run();
            p.Append(r);
            Word.Drawing drawing = new Word.Drawing();
            r.Append(drawing);
            // These dimensions work perfectly for the template document.
            WP.Inline inline = new WP.Inline(new WP.Extent() { Cx = 5486400, Cy = 3200400 });
            byte[] byteArray = spreadsheetFileName.OpenBinary();

            using (MemoryStream mem = new MemoryStream())
            {
                mem.Write(byteArray, 0, (int)byteArray.Length);

                // Open the Excel spreadsheet.
                using (SpreadsheetDocument mySpreadsheet = SpreadsheetDocument.Open(mem, true))
                {
                    // Get all of the appropriate parts.
                    WorkbookPart workbookPart = mySpreadsheet.WorkbookPart;
                    WorksheetPart worksheetPart = XLGetWorksheetPartByName(mySpreadsheet,
                       "Sheet2");
                    DrawingsPart drawingPart = worksheetPart.DrawingsPart;
                    ChartPart chartPart = (ChartPart)drawingPart.GetPartById("rId1");

                    // Clone the chart part and add it to the Word document.
                    ChartPart importedChartPart = mainPart.AddPart<ChartPart>(chartPart);
                    string relId = mainPart.GetIdOfPart(importedChartPart);

                    // The frame element contains information for the chart.
                    GraphicFrame frame =
                       drawingPart.WorksheetDrawing.Descendants<GraphicFrame>().First();
                    string chartName = frame.NonVisualGraphicFrameProperties.NonVisualDrawingProperties.Name;
                    // Clone this node so that you can add it to the Word document.
                    Draw.Graphic clonedGraphic = (Draw.Graphic)frame.Graphic.CloneNode(true);
                    ChartReference c = clonedGraphic.GraphicData.GetFirstChild<ChartReference>();
                    c.Id = relId;

                    // Give the chart a unique ID and name.
                    WP.DocProperties docPr = new WP.DocProperties();
                    docPr.Name = chartName;
                    docPr.Id = GetMaxDocPrId(mainPart) + 1;

                    // Add the chart data to the inline drawing object.
                    inline.Append(docPr, clonedGraphic);
                    drawing.Append(inline);
                }
            }
            OpenXmlElement parent = sdt.Parent;
            parent.InsertAfter(p, sdt);
            sdt.Remove();
        }
예제 #58
0
        // выполнение проверки документа по всем праметрам
        public void PerformChecking()
        {
            try
            {
                if (doc_filepath.Length > 0)
                {
                    if (ReturnNumberOfPars().Count > 100) { throw new Exception(); }
                    else
                    {
                        using (document = WordprocessingDocument.Open(openFileDialog1.FileName, true))  // документ  Open XML
                        {
                            firstParagraph =
                                document.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().First(); // определение первого абзаца текста

                            foreach (Spire.Doc.Section s in docx_doc.Sections)  // проход по всем абзацам документа
                            {
                                MarginCheck(s);  // проверка полей документа
                                PaperFormatOrientCheck(s);   // проверка формата бумаги и ориентации
                                HeaderFooterCheck(s);// проверка размеров колонтитулов
                                NumPagesCheck(s);// проверка нумерации страниц
                            }
                            PagesCheck();// проверка количества страниц
                            StylesCheck();// проверка стилей, используемых в документе
                        }
                    }
                }
            }
            catch(Exception)
            { MessageBox.Show("Количество абзацев не должно превышать 100!"); }
        }
예제 #59
0
        private void insertHABehaveTables(Boolean auto, wp.Paragraph par)
        {
            List<ReportRow> results;
            MediasCompetencia medias;
            wp.Paragraph tempPar = new wp.Paragraph(); ;
            wp.TableRow tRow;
            int count;
            wp.Run rSymbol;

            setupHABehaveTableTemplate();
            wp.Table novaTabela = tempTable.Clone() as wp.Table;

            String vh, va;

            clearParagraphText(par);

            foreach (FamiliaCompetencias fam in _Modelo.Familias.Values)
                foreach (Competencia comp in fam.Competencias.Values.Where(a => a.Type != "D"))
                {
                    if ("Orientação para Resultados" == repCalcs.getCompetenciaText(comp.CompetenciaID))
                        vh = "";

                    results = repCalcs.getAvaliacaoComportamentosCriticosExtendedOne2One(comp.CompetenciaID);
                    medias = repCalcs.getMediasCompetencia(comp.CompetenciaID);

                    tRow = tempRowHeader.Clone() as wp.TableRow;
                    setText(repCalcs.getCompetenciaText(comp.CompetenciaID), tRow.Elements<wp.TableCell>().ElementAt(0));

                    setText(medias.mS.ToString("0.00"), tRow.Elements<wp.TableCell>().ElementAt(2));
                    setText(medias.mT.ToString("0.00"), tRow.Elements<wp.TableCell>().ElementAt(3));

                    tempPar = tRow.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First();
                    rSymbol = tempPar.Elements<wp.Run>().First();

                    if (medias.mS > medias.mT)
                    {
                        rSymbol.Elements<wp.SymbolChar>().First().Char = symbUp.Char;
                    }
                    else if (medias.mS < medias.mT)
                    {
                        rSymbol.Elements<wp.SymbolChar>().First().Char = symbDw.Char;
                    }
                    else
                    {
                        rSymbol.Elements<wp.SymbolChar>().First().Char = symbH.Char;
                    }

                    novaTabela.Append(tRow);

                    tRow = tempRowHeader2.Clone() as wp.TableRow; //segundo header
                    novaTabela.Append(tRow);

                    count = 1;
                    results.RemoveAt(0); // para retirara as legendas que aqui naão são utilizadas

                    foreach (ReportRow rr in results)
                    {
                        vh = "";
                        va = "";

                        if (count % 2 == 0)
                        {
                            //par
                            tRow = tempRowPar.Clone() as wp.TableRow;
                        }
                        else
                        {
                            //impar
                            tRow = tempRowImpar.Clone() as wp.TableRow;
                        }

                        setText(rr.dados[0], tRow.Elements<wp.TableCell>().ElementAt(0));

                        tempPar = tRow.Elements<wp.TableCell>().ElementAt(1).Elements<wp.Paragraph>().First();
                        rSymbol = tempPar.Elements<wp.Run>().First();

                        if (rr.dados[6] == "-1,00")
                            vh = "-";
                        else
                            vh = rr.dados[6];

                        if (rr.dados[7] == "-1,00")
                            va = "-";
                        else va = rr.dados[7];

                        setText(vh, tRow.Elements<wp.TableCell>().ElementAt(2));
                        setText(va, tRow.Elements<wp.TableCell>().ElementAt(3));

                        // o dados de 7 e o dados de 6 podem viR A nullo

                        if (va != "-" && vh != "-" && rr.dados[7] != null && rr.dados[6] != null)
                        {
                            if (float.Parse(rr.dados[6].Replace(",", ".")) > float.Parse(rr.dados[7].Replace(",", ".")))
                            {
                                rSymbol.Elements<wp.SymbolChar>().First().Char = symbUp.Char;
                                CountUps++;
                            }
                            else if (float.Parse(rr.dados[6].Replace(",", ".")) < float.Parse(rr.dados[7].Replace(",", ".")))
                            {
                                rSymbol.Elements<wp.SymbolChar>().First().Char = symbDw.Char;
                                CountDown++;
                            }
                            else
                            {
                                rSymbol.Elements<wp.SymbolChar>().First().Char = symbH.Char;
                                CountHoriz++;
                            }
                        }
                        else
                            rSymbol.Elements<wp.SymbolChar>().First().Char = "F09F";

                        novaTabela.Append(tRow);
                        count++;
                    }

                    // colocar um parágrafo
                    novaTabela.Append(tempParagraph.Clone() as wp.Paragraph);
                }

            par.Append(novaTabela);
        }
예제 #60
-1
        public static DocumentFormat.OpenXml.OpenXmlElement[] GetFormattedChapter(Chapter chapter)
        {
            if(!stylesAdded) StyleCreator.AddStylePart();

            List<OpenXmlElement> result = new List<OpenXmlElement>();

            //Setting up Heading style
            Word.ParagraphProperties paraProps = new Word.ParagraphProperties();
            Word.ParagraphStyleId style = new Word.ParagraphStyleId()
            {
                Val = "Heading1"
            };
            paraProps.Append(style);

            //Adding chapter title
            Word.Paragraph para = new Word.Paragraph();
            Word.Run run = new Word.Run();
            Word.Text text = new Word.Text()
            {
                Text = chapter.Title
            };

            run.Append(text);
            para.Append(paraProps);
            para.Append(run);

            result.Add(para);

            //Add all child elements
            foreach (Element element in chapter.SubElements)
            {
                if (element.GetElementType() == ElementType.MultiColumnSection)
                {
                    result.AddRange(MultiColumnSectionFormatter.GetFormattedSection((MultiColumnSection)element));
                }
                else if (element.GetElementType() == ElementType.Section) result.AddRange(SectionFormatter.GetFormattedSection((Section)element));

                else throw new InvalidSubFeatureException( chapter.GetElementType().ToString() , element.GetElementType().ToString());
            }

            return result.ToArray();
        }