示例#1
0
        private IEnumerable <T> SetChartSeries <T>(OpenXmlCompositeElement chart, int newSeriesCount, bool addNewIfRequired) where T : OpenXmlCompositeElement
        {
            var seriesList         = chart.Elements <T>();
            int currentSeriesCount = seriesList.Count();

            if (currentSeriesCount > newSeriesCount)
            {
                //chart on template has more series than in the data, remove last x series
                int seriesToRemove = currentSeriesCount - newSeriesCount;
                for (int i = 0; i < seriesToRemove; i++)
                {
                    chart.RemoveChild <T>(seriesList.Last());
                }
                seriesList = chart.Elements <T>();
            }
            else
            if (addNewIfRequired && currentSeriesCount < newSeriesCount)
            {
                //chart on the template has fewer series so we need to add some by clonning the last one
                for (int i = 0; i < newSeriesCount - currentSeriesCount; i++)
                {
                    var lastSeries       = chart.Elements <T>().Last();
                    var seriesClone      = (T)lastSeries.CloneNode(true);
                    var lastSeriesIndex  = lastSeries.FirstElement <DocumentFormat.OpenXml.Drawing.Charts.Index>();
                    var seriesCloneIndex = seriesClone.FirstElement <DocumentFormat.OpenXml.Drawing.Charts.Index>();
                    seriesCloneIndex.Val = new UInt32Value(lastSeriesIndex.Val.Value + 1);
                    var lastSeriesOrder  = lastSeries.FirstElement <DocumentFormat.OpenXml.Drawing.Charts.Order>();
                    var seriesCloneOrder = seriesClone.FirstElement <DocumentFormat.OpenXml.Drawing.Charts.Order>();
                    seriesCloneOrder.Val = new UInt32Value(lastSeriesOrder.Val.Value + 1);
                    chart.InsertAfter(seriesClone, lastSeries);
                }
                seriesList = chart.Elements <T>();
            }
            return(chart.Elements <T>());
        }
示例#2
0
 public OpenXmlCompositeElement NewRun(OpenXmlCompositeElement runProps, string text, SpaceProcessingModeValues spaceMode)
 {
     return(new W.Run(runProps, new W.Text(text)
     {
         Space = spaceMode
     }));
 }
        private static PlaceholderFontData FromSlideXmlElement(OpenXmlCompositeElement xmlShape)
        {
            var result    = new PlaceholderFontData();
            var ph        = xmlShape.Descendants <P.PlaceholderShape>().First();
            var phTypeXml = ph.Type;

            // TYPE
            if (phTypeXml == null)
            {
                result.PlaceholderType = PlaceholderType.Custom;
            }
            else
            {
                // Simple title and centered title placeholders were united
                if (phTypeXml == P.PlaceholderValues.Title || phTypeXml == P.PlaceholderValues.CenteredTitle)
                {
                    result.PlaceholderType = PlaceholderType.Title;
                }
                else
                {
                    result.PlaceholderType = Enum.Parse <PlaceholderType>(phTypeXml.Value.ToString());
                }
            }

            // INDEX
            if (ph.Index != null)
            {
                result.Index = (int)ph.Index.Value;
            }

            return(result);
        }
示例#4
0
 private static SdtElement FindSdt(OpenXmlCompositeElement parent, string name)
 {
     return(parent
            .Descendants <SdtElement>()
            .Where(o => !o.Elements <SdtProperties>().First().Elements <SdtRepeatedSectionItem>().Any())
            .FirstOrDefault(o => ResolveTemplateFieldName(o.Elements <SdtProperties>().First()) == name));
 }
        public static TElement Get <TElement>(this CompiledParticle compiled, OpenXmlCompositeElement element)
            where TElement : OpenXmlElement
        {
            if (compiled is null)
            {
                return(null);
            }

            var child = element.FirstChild;

            if (child is null)
            {
                return(null);
            }

            do
            {
                if (child.GetType() == typeof(TElement))
                {
                    return((TElement)child);
                }

                child = child.Next;
            } while (child != element.FirstChild);

            return(null);
        }
示例#6
0
 public CharacterMap(OpenXmlCompositeElement ce)
 {
     _rootElement = ce;
     CreateMap(_rootElement);
     _text   = _textBuilder.ToString();
     IsDirty = false;
 }
示例#7
0
        public static string GetText(this OpenXmlCompositeElement ce)
        {
            var sb = new StringBuilder();

            GetTextRecursive(ce, sb);
            return(sb.ToString());
        }
示例#8
0
        private GeometryType ForCompositeElement(OpenXmlCompositeElement sdkCompositeElement, P.ShapeProperties spPr)
        {
            var t2D = spPr.Transform2D;

            if (t2D != null)
            {
                var presetGeometry = spPr.GetFirstChild <PresetGeometry>();
                // Placeholder can have transform on the slide, without having geometry
                if (presetGeometry == null)
                {
                    if (spPr.OfType <CustomGeometry>().Any())
                    {
                        return(GeometryType.Custom);
                    }
                    return(FromLayout());
                }

                var name = presetGeometry.Preset.Value.ToString();
                Enum.TryParse(name, true, out GeometryType geometryType);
                return(geometryType);
            }

            return(FromLayout());

            GeometryType FromLayout()
            {
                var placeholderLocationData = _phService.TryGet(sdkCompositeElement);

                if (placeholderLocationData == null)
                {
                    return(GeometryType.Rectangle);
                }
                return(placeholderLocationData.Geometry);
            }
        }
        private static void AddRows(OpenXmlCompositeElement sheet, int maxCount, int columns)
        {
            var maxIndex = sheet.Elements <Row>()
                           .Select(r => r.RowIndex.Value).Max();
            var count = sheet.Elements <Row>()
                        .Count();

            for (var i = count; i <= maxCount; i++)
            {
                var row = new Row {
                    RowIndex = ++maxIndex
                };

                for (var j = 1; j < columns + 1; j++)
                {
                    var cell = new Cell
                    {
                        DataType      = CellValues.String,
                        CellValue     = new CellValue(string.Empty),
                        CellReference = GetExcelColumnName(j) + row.RowIndex
                    };
                    row.AppendChild(cell);
                }
                sheet.AppendChild(row);
            }
        }
示例#10
0
文件: OXmlDoc.cs 项目: 24/source_04
        private void OpenFooter(OXmlOpenFooterElement element)
        {
            CreateSectionProperties();
            //if (element.Header)
            //{
            //HeaderPart headerPart = _mainPart.AddNewPart<HeaderPart>();
            //OpenXmlCompositeElement header = new Header();
            //headerPart.Header = (Header)header;
            //string headerPartId = _mainPart.GetIdOfPart(headerPart);
            //_sectionProperties.AppendChild(new HeaderReference { Id = headerPartId, Type = element.HeaderType });
            //}
            //else
            //{
            FooterPart footerPart          = _mainPart.AddNewPart <FooterPart>();
            OpenXmlCompositeElement footer = new Footer();

            footerPart.Footer = (Footer)footer;
            string footerPartId = _mainPart.GetIdOfPart(footerPart);

            _sectionProperties.AppendChild(new FooterReference {
                Id = footerPartId, Type = element.FooterType
            });
            //}
            AddHeaderFooterNamespaceDeclaration((OpenXmlPartRootElement)footer);

            SetHeaderFooterProperties(element.FooterType);

            _element = footer;
            //_headerFooter = true;
            _currentElement = OXmlDocElementType.Footer;
        }
示例#11
0
        private static void BindSerie(OpenXmlCompositeElement serie, Data.DataRow dataRow, int index)
        {
            serie.Descendants <Charts.Formula>().ToList().ForEach(f => f.Remove());

            serie.GetFirstChild <Charts.Index>().Val = new UInt32Value((uint)index);
            serie.GetFirstChild <Charts.Order>().Val = new UInt32Value((uint)index);

            var setTxt = serie.Descendants <Charts.SeriesText>().SingleEx();

            setTxt.StringReference.Descendants <Charts.NumericValue>().SingleEx().Text = dataRow[0]?.ToString();

            {
                var cat = serie.Descendants <Charts.CategoryAxisData>().SingleEx();
                cat.Descendants <Charts.PointCount>().SingleEx().Val = new UInt32Value((uint)dataRow.Table.Columns.Count - 1);
                var catValues = cat.Descendants <Charts.StringPoint>().ToList();
                SynchronizeNodes(catValues, dataRow.Table.Columns.Cast <Data.DataColumn>().Skip(1).ToList(),
                                 (sp, col, i, isCloned) =>
                {
                    sp.Index = new UInt32Value((uint)i);
                    sp.Descendants <Charts.NumericValue>().Single().Text = col.ColumnName;
                });
            }

            {
                var vals = serie.Descendants <Charts.Values>().SingleEx();
                vals.Descendants <Charts.PointCount>().SingleEx().Val = new UInt32Value((uint)dataRow.Table.Columns.Count - 1);
                var valsValues = vals.Descendants <Charts.NumericPoint>().ToList();
                SynchronizeNodes(valsValues, dataRow.ItemArray.Skip(1).ToList(),
                                 (sp, val, i, isCloned) =>
                {
                    sp.Index = new UInt32Value((uint)i);
                    sp.Descendants <Charts.NumericValue>().Single().Text = ToStringLocal(val);
                });
            }
        }
        public IInnerTransform FromComposite(OpenXmlCompositeElement sdkCompositeElement)
        {
            IInnerTransform innerTransform;
            var             t2d = sdkCompositeElement.Descendants <A.Transform2D>().FirstOrDefault();

            if (t2d != null)
            {
                // Group
                if (sdkCompositeElement.Parent is P.GroupShape groupShape)
                {
                    innerTransform = new NonPlaceholderGroupedTransform(sdkCompositeElement, groupShape);
                }
                // ShapeTree
                else
                {
                    innerTransform = new NonPlaceholderTransform(sdkCompositeElement);
                }
            }
            else
            {
                var placeholderLocationData = _phService.TryGet(sdkCompositeElement);
                innerTransform = new PlaceholderTransform(placeholderLocationData);
            }

            return(innerTransform);
        }
示例#13
0
        public override IShape Create(OpenXmlCompositeElement pShapeTreeChild, SCSlide slide)
        {
            P.Picture pPicture;
            if (pShapeTreeChild is P.Picture treePic)
            {
                pPicture = treePic;
            }
            else
            {
                var framePic = pShapeTreeChild.Descendants <P.Picture>().FirstOrDefault();
                pPicture = framePic;
            }

            if (pPicture != null)
            {
                var pBlipFill    = pPicture.GetFirstChild <P.BlipFill>();
                var blipRelateId = pBlipFill?.Blip?.Embed?.Value;
                if (blipRelateId == null)
                {
                    return(null);
                }

                var spContext = _shapeContextBuilder.Build(pShapeTreeChild);
                var picture   = new SlidePicture(slide, blipRelateId, spContext, pPicture);

                return(picture);
            }

            return(Successor?.Create(pShapeTreeChild, slide));
        }
示例#14
0
        internal virtual OpenXmlCompositeElement CreateOpenXmlCompositeElement()
        {
            // TODO: Instantiate an appropriate concrete class.
            OpenXmlCompositeElement target = null;

            return(target);
        }
示例#15
0
 /// <summary>
 /// Recursive function to dive down an XML tree and look for any NumberReference. When it finds one it will replace the original
 /// source worksheet (and/or file reference) to the new worksheet name.
 /// This assumes all data sources are going to be updated to the new worksheet name. Will break any data source references
 /// that point to external files.
 /// </summary>
 /// <param name="element">Element to look for NumberReferences on.</param>
 /// <param name="oldSourceName">Old name of the source.</param>
 /// <param name="newSourceName">New name of the source.</param>
 /// <param name="tableRowCount">The table row count.</param>
 public static void UpdateDataSourcesForChildren(OpenXmlCompositeElement element, string oldSourceName, string newSourceName, int?tableRowCount)
 {
     foreach (var child in element.ChildElements)
     {
         if (child is DocumentFormat.OpenXml.Drawing.Charts.NumberReference)
         {
             DocumentFormat.OpenXml.Drawing.Charts.NumberReference reference = (DocumentFormat.OpenXml.Drawing.Charts.NumberReference)child;
             reference.Formula.Text = UpdateFormula(reference.Formula.Text, oldSourceName, newSourceName, tableRowCount);
         }
         else if (child is DocumentFormat.OpenXml.Drawing.Charts.StringReference)
         {
             DocumentFormat.OpenXml.Drawing.Charts.StringReference reference = (DocumentFormat.OpenXml.Drawing.Charts.StringReference)child;
             reference.Formula.Text = UpdateFormula(reference.Formula.Text, oldSourceName, newSourceName, tableRowCount);
         }
         else if (child is DocumentFormat.OpenXml.Drawing.Charts.MultiLevelStringReference)
         {
             DocumentFormat.OpenXml.Drawing.Charts.MultiLevelStringReference reference = (DocumentFormat.OpenXml.Drawing.Charts.MultiLevelStringReference)child;
             reference.Formula.Text = UpdateFormula(reference.Formula.Text, oldSourceName, newSourceName, tableRowCount);
         }
         else if (child != null && typeof(OpenXmlCompositeElement).IsAssignableFrom(child.GetType()) && ((OpenXmlCompositeElement)child).HasChildren)
         {
             UpdateDataSourcesForChildren((OpenXmlCompositeElement)child, oldSourceName, newSourceName, tableRowCount);
         }
     }
 }
示例#16
0
        public static List <InsertionPoint> FindAll(OpenXmlCompositeElement elements)
        {
            var list = new List <InsertionPoint>();

            FindAll(elements, list);
            return(list);
        }
示例#17
0
 internal ParticleCollection(Type type, CompiledParticle compiled, OpenXmlCompositeElement element)
 {
     _type        = type;
     _element     = element;
     _compiled    = compiled;
     _elementPath = compiled.Find(type);
 }
示例#18
0
 /// <summary>
 /// Initializes an instance of the <see cref="TextFrame"/>.
 /// </summary>
 public TextFrame(IShapeContext spContext, OpenXmlCompositeElement compositeElement)
 {
     _spContext = spContext ?? throw new ArgumentNullException(nameof(spContext));
     Check.NotNull(compositeElement, nameof(compositeElement));
     ParseParagraphs(compositeElement);
     _text = new Lazy <string>(GetText);
 }
示例#19
0
        /// <summary>
        /// Apply all the current Html tag (Run properties) to the specified run.
        /// </summary>
        public override void ApplyTags(OpenXmlCompositeElement run)
        {
            if (tags.Count == 0 && DefaultRunStyle == null)
            {
                return;
            }

            RunProperties properties = run.GetFirstChild <RunProperties>();

            if (properties == null)
            {
                run.PrependChild <RunProperties>(properties = new RunProperties());
            }

            var en = tags.GetEnumerator();

            while (en.MoveNext())
            {
                TagsAtSameLevel tagsOfSameLevel = en.Current.Value.Peek();
                foreach (OpenXmlElement tag in tagsOfSameLevel.Array)
                {
                    SetProperties(properties, tag.CloneNode(true));
                }
            }

            if (this.DefaultRunStyle != null)
            {
                properties.RunStyle = new RunStyle()
                {
                    Val = this.DefaultRunStyle
                }
            }
            ;
        }
示例#20
0
        private readonly OpenXmlCompositeElement textBodyCompositeElement; // instance of A.TextBody or P.TextBody class

        internal SCTextBox(OpenXmlCompositeElement textBodyCompositeElement, ITextBoxContainer parentTextBoxContainer)
        {
            this.text = new Lazy <string>(this.GetText);
            this.textBodyCompositeElement = textBodyCompositeElement;
            this.Paragraphs             = new ParagraphCollection(this.textBodyCompositeElement, this);
            this.ParentTextBoxContainer = parentTextBoxContainer;
        }
        //____________________________________________________________________
        //
        /// <summary>
        /// Apply all the current Html tag to the specified table cell.
        /// </summary>
        public override void ApplyTags(OpenXmlCompositeElement tableCell)
        {
            if (tags.Count > 0)
            {
                TableCellProperties properties = tableCell.GetFirstChild<TableCellProperties>();
                if (properties == null) tableCell.PrependChild<TableCellProperties>(properties = new TableCellProperties());

                var en = tags.GetEnumerator();
                while (en.MoveNext())
                {
                    TagsAtSameLevel tagsOfSameLevel = en.Current.Value.Peek();
                    foreach (OpenXmlElement tag in tagsOfSameLevel.Array)
                        properties.Append(tag.CloneNode(true));
                }
            }

            // Apply some style attributes on the unique Paragraph tag contained inside a table cell.
            if (tagsParagraph.Count > 0)
            {
                Paragraph p = tableCell.GetFirstChild<Paragraph>();
                ParagraphProperties properties = p.GetFirstChild<ParagraphProperties>();
                if (properties == null) p.PrependChild<ParagraphProperties>(properties = new ParagraphProperties());

                var en = tagsParagraph.GetEnumerator();
                while (en.MoveNext())
                {
                    TagsAtSameLevel tagsOfSameLevel = en.Current.Value.Peek();
                    foreach (OpenXmlElement tag in tagsOfSameLevel.Array)
                        properties.Append(tag.CloneNode(true));
                }
            }
        }
示例#22
0
        /// <summary>
        /// Assigns the section properties.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="secProperties">The sec properties.</param>
        private static void AssignSectionProperties(OpenXmlCompositeElement document, OpenXmlElement secProperties)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            if (secProperties == null)
            {
                return;
            }

            var pageSize = secProperties.Descendants <PageSize>().FirstOrDefault();

            if (pageSize != null)
            {
                pageSize.Remove();
            }

            var pageMargin = secProperties.Descendants <PageMargin>().FirstOrDefault();

            if (pageMargin != null)
            {
                pageMargin.Remove();
            }

            document.AppendChild(new Paragraph(new ParagraphProperties(new SectionProperties(pageSize, pageMargin))));
        }
示例#23
0
        public void RemoveContentControlsAndKeepContents(OpenXmlCompositeElement compositeElement, XmlElement customXmlPartDocElement)
        {
            if (compositeElement == null)
            {
                throw new ArgumentNullException("compositeElement");
            }

            SdtElement acompositeElement = compositeElement as SdtElement;

            if (acompositeElement != null)
            {
                var elementsList = this.RemoveContentControlAndKeepContents(acompositeElement, customXmlPartDocElement);

                foreach (var innerCompositeElement in elementsList)
                {
                    this.RemoveContentControlsAndKeepContents(innerCompositeElement, customXmlPartDocElement);
                }
            }
            else
            {
                var childCompositeElements = compositeElement.Elements <OpenXmlCompositeElement>().ToList();

                foreach (var childCompositeElement in childCompositeElements)
                {
                    this.RemoveContentControlsAndKeepContents(childCompositeElement, customXmlPartDocElement);
                }
            }
        }
示例#24
0
        // Return a list of possible placeholders (i.e. empty text elements).
        private static List <Text> GetPlaceholders(OpenXmlCompositeElement ce)
        {
            var list = new List <Text>();

            GetPlaceholdersRecursive(ce, list);
            return(list);
        }
示例#25
0
        /// <summary>
        /// Gets
        /// </summary>
        /// <param name="sdkCompositeElement"></param>
        /// <returns></returns>
        public ILocation FromComposite(OpenXmlCompositeElement sdkCompositeElement)
        {
            Check.NotNull(sdkCompositeElement, nameof(sdkCompositeElement));

            ILocation innerTransform;
            var       aTransform = sdkCompositeElement.Descendants <A.Transform2D>().FirstOrDefault();

            if (aTransform != null ||
                sdkCompositeElement.Descendants <P.Transform>().FirstOrDefault() != null)   // p:graphicFrame contains p:xfrm
            {
                // Group
                if (sdkCompositeElement.Parent is P.GroupShape groupShape)
                {
                    innerTransform = new NonPlaceholderGroupedTransform(sdkCompositeElement, groupShape);
                }
                // ShapeTree
                else
                {
                    innerTransform = new NonPlaceholderTransform(sdkCompositeElement);
                }
            }
            else
            {
                var placeholderLocationData = _phService.TryGetLocation(sdkCompositeElement);
                innerTransform = new PlaceholderTransform(placeholderLocationData);
            }

            return(innerTransform);
        }
示例#26
0
        FromCompositeElement(
            OpenXmlCompositeElement compositeElement)     // TODO: set annotation that about it cannot be NULL
        {
            // Get <a:lvlXpPr> elements, eg. <a:lvl1pPr>, <a:lvl2pPr>
            IEnumerable <OpenXmlElement> lvlParagraphPropertyList = compositeElement.Elements()
                                                                    .Where(e => e.LocalName.StartsWith("lvl", StringComparison.Ordinal));

            var lvlToFontData = new Dictionary <int, FontData>();

            foreach (OpenXmlElement textPr in lvlParagraphPropertyList)
            {
                A.DefaultRunProperties aDefRPr = textPr.GetFirstChild <A.DefaultRunProperties>();

                Int32Value         fontSize          = aDefRPr?.FontSize;
                BooleanValue       isBold            = aDefRPr?.Bold;
                BooleanValue       isItalic          = aDefRPr?.Italic;
                A.LatinFont        aLatinFont        = aDefRPr?.GetFirstChild <A.LatinFont>();
                A.RgbColorModelHex aRgbColorModelHex = aDefRPr?.GetFirstChild <A.SolidFill>()?.RgbColorModelHex;
                A.SchemeColor      aSchemeColor      = aDefRPr?.GetFirstChild <A.SolidFill>()?.SchemeColor;

#if NETSTANDARD2_0
                var lvl = int.Parse(textPr.LocalName[3].ToString(System.Globalization.CultureInfo.CurrentCulture), System.Globalization.CultureInfo.CurrentCulture);
#else
                // fourth character of LocalName contains level number, example: "lvl1pPr -> 1, lvl2pPr -> 2, etc."
                ReadOnlySpan <char> localNameAsSpan = textPr.LocalName.AsSpan();
                int lvl = int.Parse(localNameAsSpan.Slice(3, 1));
#endif
                lvlToFontData.Add(lvl, new FontData(fontSize, aLatinFont, isBold, isItalic, aRgbColorModelHex, aSchemeColor));
            }

            return(lvlToFontData);
        }
示例#27
0
 internal static void ApplyDefaultBorders(OpenXmlCompositeElement element)
 {
     ApplyDefaultBorder <TopBorder>(element);
     ApplyDefaultBorder <LeftBorder>(element);
     ApplyDefaultBorder <BottomBorder>(element);
     ApplyDefaultBorder <RightBorder>(element);
 }
示例#28
0
 /// <summary>
 /// Lấy màu border
 /// </summary>
 /// <returns></returns>
 public ColorBase GetBorderBrushColor(pp.Shape shape, OpenXmlCompositeElement shapeTag, OpenXmlPart openXmlPart)
 {
     if (shapeTag == null)
     {
         return(null);
     }
     if (shapeTag is P.Shape _shape)
     {
         if (_shape.ShapeProperties != null)
         {
             foreach (var item in _shape.ShapeProperties)
             {
                 if (item is Outline outline)
                 {
                     return(GetSolidColor(shape.Line.ForeColor));
                 }
             }
             if (_shape.ShapeStyle?.FillReference?.SchemeColor != null)
             {
                 return(GetSolidColor(shape.Line.ForeColor));
             }
         }
     }
     return(new SolidColor()
     {
         Name = "Transparent"
     });
 }
        /// <summary>
        /// Apply all the current Html tag (Paragraph properties) to the specified paragrah.
        /// </summary>
        public override void ApplyTags(OpenXmlCompositeElement paragraph)
        {
            if (tags.Count == 0)
            {
                return;
            }

            ParagraphProperties properties = paragraph.GetFirstChild <ParagraphProperties>();

            if (properties == null)
            {
                paragraph.PrependChild <ParagraphProperties>(properties = new ParagraphProperties());
            }

            var en = tags.GetEnumerator();

            while (en.MoveNext())
            {
                TagsAtSameLevel tagsOfSameLevel = en.Current.Value.Peek();
                foreach (OpenXmlElement tag in tagsOfSameLevel.Array)
                {
                    SetProperties(properties, tag.CloneNode(true));
                }
            }
        }
        //____________________________________________________________________
        //

        /// <summary>
        /// Apply all the current Html tag to the specified table cell.
        /// </summary>
        public override void ApplyTags(OpenXmlCompositeElement tableCell)
        {
            if (tags.Count > 0)
            {
                TableCellProperties properties = tableCell.GetFirstChild <TableCellProperties>();
                if (properties == null)
                {
                    tableCell.PrependChild <TableCellProperties>(properties = new TableCellProperties());
                }

                var en = tags.GetEnumerator();
                while (en.MoveNext())
                {
                    TagsAtSameLevel tagsOfSameLevel = en.Current.Value.Peek();
                    foreach (OpenXmlElement tag in tagsOfSameLevel.Array)
                    {
                        SetProperties(properties, tag.CloneNode(true));
                    }
                }
            }

            // Apply some style attributes on the unique Paragraph tag contained inside a table cell.
            Paragraph p = tableCell.GetFirstChild <Paragraph>();

            paragraphStyle.ApplyTags(p);
        }
示例#31
0
        /// <summary>
        /// Bolds the specified text in the target element
        /// </summary>
        /// <param name="element">Target element</param>
        /// <param name="text">Text to be bolded</param>
        private static void SetBoldText(OpenXmlCompositeElement element, string text)
        {
            foreach (var run in element.Descendants <Run>())
            {
                var txt = run.GetFirstChild <Text>();

                if (txt != null)
                {
                    if (txt.Text.Contains(text) && txt.Text != text)
                    {
                        var indexOfText   = txt.Text.IndexOf(text);
                        var runBefore     = (Run)run.Clone();
                        var runBeforeText = runBefore.GetFirstChild <Text>();
                        runBeforeText.Space = SpaceProcessingModeValues.Preserve;
                        runBeforeText.Text  = txt.Text.Substring(0, indexOfText == 0 ? 0 : indexOfText);
                        var runAfter     = (Run)run.Clone();
                        var runAfterText = runAfter.GetFirstChild <Text>();
                        runAfterText.Space = SpaceProcessingModeValues.Preserve;
                        runAfterText.Text  = txt.Text.Substring(indexOfText + text.Length);
                        run.Parent.InsertBefore(runBefore, run);
                        run.Parent.InsertAfter(runAfter, run);

                        txt.Text = text;
                        run.RunProperties.Bold = new Bold();
                    }
                    else if (txt.Text == text)
                    {
                        run.RunProperties.Bold = new Bold();
                    }
                }
            }
        }
        /// <summary>
        /// Apply all the current Html tag (Paragraph properties) to the specified paragrah.
        /// </summary>
        public override void ApplyTags(OpenXmlCompositeElement paragraph)
        {
            if (tags.Count == 0) return;

            ParagraphProperties properties = paragraph.GetFirstChild<ParagraphProperties>();
            if (properties == null) paragraph.PrependChild<ParagraphProperties>(properties = new ParagraphProperties());

            var en = tags.GetEnumerator();
            while (en.MoveNext())
            {
                TagsAtSameLevel tagsOfSameLevel = en.Current.Value.Peek();
                foreach (OpenXmlElement tag in tagsOfSameLevel.Array)
                    properties.Append(tag.CloneNode(true));
            }
        }
        /// <summary>
        /// Apply all the current Html tag (Run properties) to the specified run.
        /// </summary>
        public override void ApplyTags(OpenXmlCompositeElement run)
        {
            if (tags.Count == 0 && DefaultRunStyle == null) return;

            RunProperties properties = run.GetFirstChild<RunProperties>();
            if (properties == null) run.PrependChild<RunProperties>(properties = new RunProperties());

            var en = tags.GetEnumerator();
            while (en.MoveNext())
            {
                TagsAtSameLevel tagsOfSameLevel = en.Current.Value.Peek();
                foreach (OpenXmlElement tag in tagsOfSameLevel.Array)
                    properties.Append(tag.CloneNode(true));
            }

            if (this.DefaultRunStyle != null)
                properties.Append(new RunStyle() { Val = this.DefaultRunStyle });
        }
示例#34
0
        /// <summary>
        /// Sets the SDT content keeping permission elements.
        /// </summary>
        /// <param name="openXmlCompositeElement">The open XML composite element.</param>
        /// <param name="newChildren">The new children.</param>
        private void SetSdtContentKeepingPermissionElements(OpenXmlCompositeElement openXmlCompositeElement, List<OpenXmlElement> newChildren)
        {
            PermStart start = openXmlCompositeElement.Descendants<PermStart>().FirstOrDefault();
            PermEnd end = openXmlCompositeElement.Descendants<PermEnd>().FirstOrDefault();
            openXmlCompositeElement.RemoveAllChildren();

            if (start != null)
            {
                openXmlCompositeElement.AppendChild(start);
            }

            foreach (var newChild in newChildren)
            {
                openXmlCompositeElement.AppendChild(newChild);
            }

            if (end != null)
            {
                openXmlCompositeElement.AppendChild(end);
            }
        }
示例#35
0
 /// <summary>
 /// Add a new paragraph, table, ... to the list of processed paragrahs. This method takes care of 
 /// adding the new element to the current table if it exists.
 /// </summary>
 private void AddParagraph(OpenXmlCompositeElement element)
 {
     if (tables.HasContext)
         tables.CurrentTable.GetLastChild<TableRow>().GetLastChild<TableCell>().Append(element);
     else
         this.paragraphs.Add(element);
 }
        private void AddCell(OpenXmlCompositeElement row, Action<ICellContextBuilder> options, TableCellProperties cellProperties)
        {
            var builder = new DocxDocumentCellContextBuilder(Document, cellProperties);

            options(builder);
            row.AppendChild(builder.ToElement());
        }
示例#37
0
        /// <summary>
        /// Creates the run.
        /// </summary>
        /// <param name="openXmlCompositeElement">The open XML composite element.</param>
        /// <param name="content">The content.</param>
        /// <returns>Returns a run object</returns>
        private static Run CreateRun(OpenXmlCompositeElement openXmlCompositeElement, string content)
        {
            var runProperties = openXmlCompositeElement.Descendants<RunProperties>().FirstOrDefault();

            var run = runProperties != null
                          ? new Run(runProperties.CloneNode(true), new Text(content))
                          : new Run(new Text(content));

            return run;
        }
示例#38
0
        /// <summary>
        /// Sets the SDT content keeping permission elements.
        /// </summary>
        /// <param name="openXmlCompositeElement">The open XML composite element.</param>
        /// <param name="newChildren">The new children.</param>
        private static void SetSdtContentKeepingPermissionElements(OpenXmlCompositeElement openXmlCompositeElement, IEnumerable<Run> newChildren)
        {
            var start = openXmlCompositeElement.Descendants<PermStart>().FirstOrDefault();
            var end = openXmlCompositeElement.Descendants<PermEnd>().FirstOrDefault();
            openXmlCompositeElement.RemoveAllChildren();

            if (start != null)
            {
                openXmlCompositeElement.AppendChild(start);
            }

            foreach (var newChild in newChildren)
            {
                openXmlCompositeElement.AppendChild(newChild);
            }

            if (end != null)
            {
                openXmlCompositeElement.AppendChild(end);
            }
        }
示例#39
0
        /// <summary>
        /// Assigns the section properties.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="secProperties">The sec properties.</param>
        private static void AssignSectionProperties(OpenXmlCompositeElement document, OpenXmlElement secProperties)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            if (secProperties == null)
            {
                return;
            }

            var pageSize = secProperties.Descendants<PageSize>().FirstOrDefault();

            if (pageSize != null)
            {
                pageSize.Remove();
            }

            var pageMargin = secProperties.Descendants<PageMargin>().FirstOrDefault();

            if (pageMargin != null)
            {
                pageMargin.Remove();
            }

            document.AppendChild(new Paragraph(new ParagraphProperties(new SectionProperties(pageSize, pageMargin))));
        }
示例#40
0
        /// <summary>
        /// Creates the paragraph.
        /// </summary>
        /// <param name="openXmlCompositeElement">The open XML composite element.</param>
        /// <param name="runs">The runs.</param>
        /// <returns>Returns the paragraph element</returns>
        private static Paragraph CreateParagraph(OpenXmlCompositeElement openXmlCompositeElement, List<Run> runs)
        {
            var paragraphProperties = openXmlCompositeElement.Descendants<ParagraphProperties>().FirstOrDefault();
            Paragraph para;

            if (paragraphProperties != null)
            {
                para = new Paragraph(paragraphProperties.CloneNode(true));
                foreach (var run in runs)
                {
                    para.AppendChild(run);
                }
            }
            else
            {
                para = new Paragraph();
                foreach (var run in runs)
                {
                    para.AppendChild(run);
                }
            }

            return para;
        }
示例#41
0
        /// <summary>
        /// Adds the runs to SDT content cell.
        /// </summary>
        /// <param name="sdtContentCell">The SDT content cell.</param>
        /// <param name="runs">The runs.</param>
        private static void AddRunsToSdtContentCell(OpenXmlCompositeElement sdtContentCell, IEnumerable<Run> runs)
        {
            var cell = new TableCell();
            var para = new Paragraph();
            para.RemoveAllChildren();

            foreach (var run in runs)
            {
                para.AppendChild(run);
            }

            cell.AppendChild(para);
            SetSdtContentKeepingPermissionElements(sdtContentCell, cell);
        }
示例#42
0
        public void RemoveContentControlsAndKeepContents(OpenXmlCompositeElement compositeElement, XmlElement customXmlPartDocElement)
        {
            if (compositeElement == null)
            {
                throw new ArgumentNullException("compositeElement");
            }

            SdtElement acompositeElement = compositeElement as SdtElement;
            if (acompositeElement != null)
            {
                var elementsList = this.RemoveContentControlAndKeepContents(acompositeElement, customXmlPartDocElement);

                foreach (var innerCompositeElement in elementsList)
                {
                    this.RemoveContentControlsAndKeepContents(innerCompositeElement, customXmlPartDocElement);
                }
            }
            else
            {
                var childCompositeElements = compositeElement.Elements<OpenXmlCompositeElement>().ToList();

                foreach (var childCompositeElement in childCompositeElements)
                {
                    this.RemoveContentControlsAndKeepContents(childCompositeElement, customXmlPartDocElement);
                }
            }
        }
示例#43
0
        /// <summary>
        /// Sets the unique content control ids.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="existingIds">The existing ids.</param>
        public static void SetUniquecontentControlIds(OpenXmlCompositeElement element, IList<int> existingIds)
        {
            var randomizer = new Random();

            foreach (var sdtId in element.Descendants<SdtId>())
            {
                if (existingIds.Contains(sdtId.Val))
                {
                    var randomId = randomizer.Next(int.MaxValue);

                    while (existingIds.Contains(randomId))
                    {
                        randomizer.Next(int.MaxValue);
                    }

                    sdtId.Val.Value = randomId;
                }
                else
                {
                    existingIds.Add(sdtId.Val);
                }
            }
        }
 /// <summary>
 /// Apply all the current Html tag (Run properties) to the specified run.
 /// </summary>
 public abstract void ApplyTags(OpenXmlCompositeElement element);
示例#45
0
 public static string CreateFooter(MainDocumentPart mainPart, OpenXmlCompositeElement element)
 {
     FooterPart footerPart = mainPart.AddNewPart<FooterPart>();
     Footer footer = new Footer();
     AddHeaderFooterNamespaceDeclaration(footer);
     if (element != null)
         footer.AppendChild(element);
     footerPart.Footer = footer;
     return mainPart.GetIdOfPart(footerPart);
 }
        /// <summary>
        /// Insert a style element inside a RunProperties, taking care of the correct sequence order as defined in the ECMA Standard.
        /// </summary>
        /// <param name="containerProperties">A RunProperties or ParagraphProperties wherein the tag will be inserted.</param>
        /// <param name="tag">The style to apply to the run.</param>
        protected void SetProperties(OpenXmlCompositeElement containerProperties, OpenXmlElement tag)
        {
            // This implementation is largely inspired by DocumentFormat.OpenXml.OpenXmlCompositeElement.SetElement which is internal.

            int tagOrder = GetTagOrder(tag);

            OpenXmlElement firstChild = containerProperties.FirstChild;
            OpenXmlElement openXmlElement = null;
            Type type = tag.GetType();

            while (firstChild != null)
            {
                bool isKnownElement = (!(firstChild is OpenXmlUnknownElement) && !(firstChild is OpenXmlMiscNode));
                if (isKnownElement)
                {
                    int num = GetTagOrder(firstChild);

                    if (num != tagOrder)
                    {
                        if (num > tagOrder) break;
                        openXmlElement = firstChild;
                    }
                    else if (!type.IsInstanceOfType(tag))
                    {
                        openXmlElement = firstChild;
                    }
                    else
                    {
                        openXmlElement = firstChild.PreviousSibling();
                        containerProperties.RemoveChild<OpenXmlElement>(firstChild);
                        break;
                    }
                }

                firstChild = firstChild.NextSibling();
            }

            if (tag != null)
                containerProperties.InsertAfter(tag, openXmlElement);
        }
示例#47
0
文件: OXmlDoc.cs 项目: labeuze/source
 private void CloseHeaderFooter()
 {
     _element = _body;
     //_headerFooter = false;
     _currentElement = OXmlDocElementType.Body;
 }
示例#48
0
文件: OXmlDoc.cs 项目: labeuze/source
        private void OpenFooter(OXmlOpenFooterElement element)
        {
            CreateSectionProperties();
            //if (element.Header)
            //{
            //HeaderPart headerPart = _mainPart.AddNewPart<HeaderPart>();
            //OpenXmlCompositeElement header = new Header();
            //headerPart.Header = (Header)header;
            //string headerPartId = _mainPart.GetIdOfPart(headerPart);
            //_sectionProperties.AppendChild(new HeaderReference { Id = headerPartId, Type = element.HeaderType });
            //}
            //else
            //{
            FooterPart footerPart = _mainPart.AddNewPart<FooterPart>();
            OpenXmlCompositeElement footer = new Footer();
            footerPart.Footer = (Footer)footer;
            string footerPartId = _mainPart.GetIdOfPart(footerPart);
            _sectionProperties.AppendChild(new FooterReference { Id = footerPartId, Type = element.FooterType });
            //}
            AddHeaderFooterNamespaceDeclaration((OpenXmlPartRootElement)footer);

            SetHeaderFooterProperties(element.FooterType);

            _element = footer;
            //_headerFooter = true;
            _currentElement = OXmlDocElementType.Footer;
        }
示例#49
0
 public static string CreateHeader(MainDocumentPart mainPart, OpenXmlCompositeElement element)
 {
     HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>();
     Header header = new Header();
     AddHeaderFooterNamespaceDeclaration(header);
     if (element != null)
         header.AppendChild(element);
     headerPart.Header = header;
     return mainPart.GetIdOfPart(headerPart);
 }
 private static void TransferChildElements(CustomXmlElement from, OpenXmlCompositeElement to)
 {
     OpenXmlElement[] elements = from.ChildElements.ToArray();
     foreach (var e in elements)
     {
         e.Remove();
     }
     to.Append(elements);
 }
示例#51
0
        /// <summary>
        /// Creates the run.
        /// </summary>
        /// <param name="openXmlCompositeElement">The open XML composite element.</param>
        /// <param name="content">The content.</param>
        /// <returns></returns>
        private static Run CreateRun(OpenXmlCompositeElement openXmlCompositeElement, string content)
        {
            RunProperties runProperties = openXmlCompositeElement.Descendants<RunProperties>().FirstOrDefault();
            Run run = null;

            if (runProperties != null)
            {
                run = new Run(runProperties.CloneNode(true), new Text(content));
            }
            else
            {
                run = new Run(new Text(content));
            }

            return run;
        }
 private void AddCell(OpenXmlCompositeElement row, Action<ICellContextBuilder> options)
 {
     var tableCellProperties = new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto });
     AddCell(row, options, tableCellProperties);
 }
示例#53
0
 /// <summary>
 /// Add a new paragraph, table, ... to the list of processed paragrahs. This method takes care of 
 /// adding the new element to the current table if it exists.
 /// </summary>
 private void AddParagraph(OpenXmlCompositeElement element)
 {
     if (tables.HasContext)
     {
         TableRow row = tables.CurrentTable.GetLastChild<TableRow>();
         if (row == null)
         {
             tables.CurrentTable.Append(row = new TableRow());
             tables.CellPosition = new Point(0, tables.CellPosition.Y + 1);
         }
         row.GetLastChild<TableCell>().Append(element);
     }
     else
         this.paragraphs.Add(element);
 }