Exemple #1
0
        private Paragraph VlozVnorenySoubor(MainDocumentPart mainPart, string strSoubor, bool blnRelativniCesta)
        {
            ExternalRelationship er = null;

            if (blnRelativniCesta)
            {
                er = mainPart.AddExternalRelationship(csSubDocument, new System.Uri(strSoubor, System.UriKind.Relative));
            }
            else
            {
                er = mainPart.AddExternalRelationship(csSubDocument, new System.Uri(strSoubor, System.UriKind.Absolute));
            }

            string sId = er.Id;

            Paragraph           p  = new Paragraph();
            ParagraphProperties pp = new ParagraphProperties();

            SectionProperties s = new SectionProperties();

            pp.Append(s);

            SubDocumentReference sdr = new SubDocumentReference()
            {
                Id = sId
            };

            p.Append(pp);
            p.Append(sdr);

            return(p);
        }
        public void Apply(OleObject ole)
        {
            _writer.WriteStartElement("o", "OLEObject", OpenXmlNamespaces.Office);

            EmbeddedObjectPart.ObjectType type;
            if (ole.ClipboardFormat == "Biff8")
            {
                type = EmbeddedObjectPart.ObjectType.Excel;
            }
            else if (ole.ClipboardFormat == "MSWordDoc")
            {
                type = EmbeddedObjectPart.ObjectType.Word;
            }
            else if (ole.ClipboardFormat == "MSPresentation")
            {
                type = EmbeddedObjectPart.ObjectType.Powerpoint;
            }
            else
            {
                type = EmbeddedObjectPart.ObjectType.Other;
            }

            //type
            if (ole.fLinked)
            {
                Uri link = new Uri(ole.Link);
                ExternalRelationship rel = _targetPart.AddExternalRelationship(OpenXmlRelationshipTypes.OleObject, link);
                _writer.WriteAttributeString("r", "id", OpenXmlNamespaces.Relationships, rel.Id);
                _writer.WriteAttributeString("Type", "Link");
                _writer.WriteAttributeString("UpdateMode", ole.UpdateMode.ToString());
            }
            else
            {
                EmbeddedObjectPart part = _targetPart.AddEmbeddedObjectPart(type);
                _writer.WriteAttributeString("r", "id", OpenXmlNamespaces.Relationships, part.RelIdToString);
                _writer.WriteAttributeString("Type", "Embed");

                //copy the object
                copyEmbeddedObject(ole, part);
            }

            //ProgID
            _writer.WriteAttributeString("ProgID", ole.Program);

            //ShapeId
            _writer.WriteAttributeString("ShapeID", _pict.ShapeContainer.GetHashCode().ToString());

            //DrawAspect
            _writer.WriteAttributeString("DrawAspect", "Content");

            //ObjectID
            _writer.WriteAttributeString("ObjectID", ole.ObjectId);

            _writer.WriteEndElement();
        }
Exemple #3
0
        public static void InsertTemplateURI(this WordprocessingDocument document, string url)
        {
            MainDocumentPart mainPart = document.MainDocumentPart;
            var uri = new Uri(url);
            DocumentSettingsPart documentSettingsPart = mainPart.DocumentSettingsPart;
            ExternalRelationship relationship         = documentSettingsPart.AddExternalRelationship(
                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", uri);

            documentSettingsPart.Settings.Append(
                new DocumentFormat.OpenXml.Wordprocessing.AttachedTemplate()
            {
                Id = relationship.Id
            });
        }
        private void HandleLinks(XmlDocument mainDoc, XmlNamespaceManager nsm)
        {
            // put the hyperlinks in places
            XmlNodeList linkNodes = mainDoc.SelectNodes("//w:hyperlink", nsm);

            foreach (XmlNode node in linkNodes)
            {
                // need to convert these three attributes
                XmlAttribute ridAttr = node.Attributes["r:id"];

                if (ridAttr != null)
                {
                    string linkRelationShipId = ridAttr.Value;

                    XmlAttribute         linkAttr    = mainDoc.CreateAttribute("w:dest", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
                    ExternalRelationship externalRel = parentDocument.Document.MainDocumentPart.ExternalRelationships.Where(rel => (rel.Id == linkRelationShipId)).FirstOrDefault();
                    if (externalRel != null)
                    {
                        linkAttr.Value = externalRel.Uri.OriginalString;
                        if (linkAttr.Value != null)
                        {
                            // Not sure if path adjustment is needed
                            //linkAttr.Value = getServerRelativePath(srcDocLibPath, linkAttr.Value);

                            XmlNode hlinkNode = mainDoc.CreateNode(XmlNodeType.Element, "w:hlink", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");

                            hlinkNode.Attributes.Append(linkAttr);

                            // copy the other attributes (such as target, tooltip, ...)
                            foreach (XmlAttribute attribute in node.Attributes)
                            {
                                // you have to clone the attribute, else it messes up the node.Attributes collection enumeration
                                hlinkNode.Attributes.Append((XmlAttribute)attribute.Clone());
                            }

                            hlinkNode.InnerXml = node.InnerXml;

                            node.ParentNode.ReplaceChild(hlinkNode, node);
                        }
                    }
                }
            }
        }
        public void Apply(ShapeOptions so)
        {
            RegularContainer slide = so.FirstAncestorWithType <Slide>();

            if (slide == null)
            {
                slide = so.FirstAncestorWithType <Note>();
            }
            if (slide == null)
            {
                slide = so.FirstAncestorWithType <Handout>();
            }
            string colorval  = "";
            string colorval2 = "";
            uint   fillType  = 0;

            if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillType))
            {
                fillType = so.OptionsByID[ShapeOptions.PropertyId.fillType].op;
            }
            switch (fillType)
            {
            case 0x0:     //solid
                string SchemeType = "";


                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillColor))
                {
                    colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillColor].op, (RegularContainer)slide, so, ref SchemeType);
                }
                else
                {
                    colorval = "FFFFFF";     //TODO: find out which color to use in this case
                }
                _writer.WriteStartElement("a", "solidFill", OpenXmlNamespaces.DrawingML);

                if (SchemeType.Length == 0)
                {
                    _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", colorval);
                }
                else
                {
                    _writer.WriteStartElement("a", "schemeClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", SchemeType);
                }

                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillOpacity) && so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op != 65536)
                {
                    _writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op / 65536 * 100000)).ToString());     //we need the percentage of the opacity (65536 means 100%)
                    _writer.WriteEndElement();
                }
                _writer.WriteEndElement();
                _writer.WriteEndElement();
                break;

            case 0x1:     //pattern
                uint           blipIndex1 = so.OptionsByID[ShapeOptions.PropertyId.fillBlip].op;
                DrawingGroup   gr1        = (DrawingGroup)this._ctx.Ppt.DocumentRecord.FirstChildWithType <PPDrawingGroup>().Children[0];
                BlipStoreEntry bse1       = (BlipStoreEntry)gr1.FirstChildWithType <BlipStoreContainer>().Children[(int)blipIndex1 - 1];
                BitmapBlip     b1         = (BitmapBlip)_ctx.Ppt.PicturesContainer._pictures[bse1.foDelay];

                _writer.WriteStartElement("a", "pattFill", OpenXmlNamespaces.DrawingML);

                _writer.WriteAttributeString("prst", Utils.getPrstForPatternCode(b1.m_bTag));     //Utils.getPrstForPattern(blipNamePattern));

                _writer.WriteStartElement("a", "fgClr", OpenXmlNamespaces.DrawingML);
                _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                _writer.WriteAttributeString("val", Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillColor].op, slide, so));
                _writer.WriteEndElement();
                _writer.WriteEndElement();

                _writer.WriteStartElement("a", "bgClr", OpenXmlNamespaces.DrawingML);
                _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBackColor))
                {
                    colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillBackColor].op, slide, so);
                }
                else
                {
                    colorval = "ffffff";     //TODO: find out which color to use in this case
                }
                _writer.WriteAttributeString("val", colorval);
                _writer.WriteEndElement();
                _writer.WriteEndElement();

                _writer.WriteEndElement();

                break;

            case 0x2:     //texture
            case 0x3:     //picture
                uint   blipIndex = 0;
                string strUrl    = "";

                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBlip))
                {
                    blipIndex = so.OptionsByID[ShapeOptions.PropertyId.fillBlip].op;
                }
                else if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.Pib))
                {
                    blipIndex = so.OptionsByID[ShapeOptions.PropertyId.Pib].op;
                }
                else if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBlipFlags) && so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBlipName))
                {
                    uint flags      = so.OptionsByID[ShapeOptions.PropertyId.fillBlipFlags].op;
                    bool comment    = !Tools.Utils.BitmaskToBool(flags, 0x1);
                    bool file       = Tools.Utils.BitmaskToBool(flags, 0x1);
                    bool url        = Tools.Utils.BitmaskToBool(flags, 0x1 << 1);
                    bool DoNotSave  = Tools.Utils.BitmaskToBool(flags, 0x1 << 2);
                    bool LinkToFile = Tools.Utils.BitmaskToBool(flags, 0x1 << 3);

                    if (url)
                    {
                        strUrl = ASCIIEncoding.ASCII.GetString(so.OptionsByID[ShapeOptions.PropertyId.fillBlipName].opComplex);
                        strUrl = strUrl.Replace("\0", "");
                    }
                }
                else
                {
                    break;
                }

                //string blipName = Encoding.UTF8.GetString(so.OptionsByID[ShapeOptions.PropertyId.fillBlipName].opComplex);
                string       rId     = "";
                DrawingGroup gr      = (DrawingGroup)this._ctx.Ppt.DocumentRecord.FirstChildWithType <PPDrawingGroup>().Children[0];
                ImagePart    imgPart = null;


                if (strUrl.Length > 0)
                {
                    ExternalRelationship er = _parentSlideMapping.targetPart.AddExternalRelationship(OpenXmlRelationshipTypes.Image, strUrl);

                    rId = er.Id;

                    _writer.WriteStartElement("a", "blipFill", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("dpi", "0");
                    _writer.WriteAttributeString("rotWithShape", "1");

                    _writer.WriteStartElement("a", "blip", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("r", "link", OpenXmlNamespaces.Relationships, rId);



                    _writer.WriteEndElement();

                    _writer.WriteElementString("a", "srcRect", OpenXmlNamespaces.DrawingML, "");

                    if (fillType == 0x3)
                    {
                        _writer.WriteStartElement("a", "stretch", OpenXmlNamespaces.DrawingML);
                        _writer.WriteElementString("a", "fillRect", OpenXmlNamespaces.DrawingML, "");
                        _writer.WriteEndElement();
                    }
                    else
                    {
                        _writer.WriteStartElement("a", "tile", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("tx", "0");
                        _writer.WriteAttributeString("ty", "0");
                        _writer.WriteAttributeString("sx", "100000");
                        _writer.WriteAttributeString("sy", "100000");
                        _writer.WriteAttributeString("flip", "none");
                        _writer.WriteAttributeString("algn", "tl");
                        _writer.WriteEndElement();
                    }

                    _writer.WriteEndElement();
                }
                else if (blipIndex <= gr.FirstChildWithType <BlipStoreContainer>().Children.Count)
                {
                    BlipStoreEntry bse = (BlipStoreEntry)gr.FirstChildWithType <BlipStoreContainer>().Children[(int)blipIndex - 1];

                    if (_ctx.Ppt.PicturesContainer._pictures.ContainsKey(bse.foDelay))
                    {
                        Record rec = _ctx.Ppt.PicturesContainer._pictures[bse.foDelay];

                        if (rec is BitmapBlip)
                        {
                            BitmapBlip b = (BitmapBlip)_ctx.Ppt.PicturesContainer._pictures[bse.foDelay];
                            imgPart = _parentSlideMapping.targetPart.AddImagePart(ShapeTreeMapping.getImageType(b.TypeCode));
                            imgPart.TargetDirectory = "..\\media";
                            System.IO.Stream outStream = imgPart.GetStream();
                            outStream.Write(b.m_pvBits, 0, b.m_pvBits.Length);
                        }
                        else
                        {
                            MetafilePictBlip b = (MetafilePictBlip)_ctx.Ppt.PicturesContainer._pictures[bse.foDelay];
                            imgPart = _parentSlideMapping.targetPart.AddImagePart(ShapeTreeMapping.getImageType(b.TypeCode));
                            imgPart.TargetDirectory = "..\\media";
                            System.IO.Stream outStream    = imgPart.GetStream();
                            byte[]           decompressed = b.Decrompress();
                            outStream.Write(decompressed, 0, decompressed.Length);
                        }

                        rId = imgPart.RelIdToString;

                        _writer.WriteStartElement("a", "blipFill", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("dpi", "0");
                        _writer.WriteAttributeString("rotWithShape", "1");

                        _writer.WriteStartElement("a", "blip", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("r", "embed", OpenXmlNamespaces.Relationships, rId);



                        _writer.WriteEndElement();

                        _writer.WriteElementString("a", "srcRect", OpenXmlNamespaces.DrawingML, "");

                        if (fillType == 0x3)
                        {
                            _writer.WriteStartElement("a", "stretch", OpenXmlNamespaces.DrawingML);
                            _writer.WriteElementString("a", "fillRect", OpenXmlNamespaces.DrawingML, "");
                            _writer.WriteEndElement();
                        }
                        else
                        {
                            _writer.WriteStartElement("a", "tile", OpenXmlNamespaces.DrawingML);
                            _writer.WriteAttributeString("tx", "0");
                            _writer.WriteAttributeString("ty", "0");
                            _writer.WriteAttributeString("sx", "100000");
                            _writer.WriteAttributeString("sy", "100000");
                            _writer.WriteAttributeString("flip", "none");
                            _writer.WriteAttributeString("algn", "tl");
                            _writer.WriteEndElement();
                        }

                        _writer.WriteEndElement();
                    }
                }
                break;

            case 0x4:     //shade
            case 0x5:     //shadecenter
            case 0x6:     //shadeshape
                _writer.WriteStartElement("a", "gradFill", OpenXmlNamespaces.DrawingML);
                _writer.WriteAttributeString("rotWithShape", "1");
                _writer.WriteStartElement("a", "gsLst", OpenXmlNamespaces.DrawingML);
                bool useFillAndBack = true;

                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillShadeColors))
                {
                    byte[] colors = so.OptionsByID[ShapeOptions.PropertyId.fillShadeColors].opComplex;

                    if (colors != null && colors.Length > 0)
                    {
                        useFillAndBack = false;
                        ShapeOptions.OptionEntry type = so.OptionsByID[ShapeOptions.PropertyId.fillShadeType];

                        UInt16 nElems      = System.BitConverter.ToUInt16(colors, 0);
                        UInt16 nElemsAlloc = System.BitConverter.ToUInt16(colors, 2);
                        UInt16 cbElem      = System.BitConverter.ToUInt16(colors, 4);

                        List <string> positions = new List <string>();

                        switch (nElems)
                        {
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                            positions.Add("0");
                            positions.Add("30000");
                            positions.Add("65000");
                            positions.Add("90000");
                            positions.Add("100000");
                            break;

                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        default:
                            positions.Add("0");
                            positions.Add("8000");
                            positions.Add("13000");
                            positions.Add("21000");
                            positions.Add("52000");
                            positions.Add("56000");
                            positions.Add("58000");
                            positions.Add("71000");
                            positions.Add("94000");
                            positions.Add("100000");
                            break;
                        }


                        string[] alphas = new string[nElems];
                        if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillOpacity))
                        {
                            decimal end   = Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op / 65536 * 100000));
                            decimal start = Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillBackOpacity].op / 65536 * 100000));
                            alphas[0] = start.ToString();
                            for (int i = 1; i < nElems - 1; i++)
                            {
                                alphas[i] = Math.Round(start + (end - start) / 3 * i).ToString();
                            }
                            //alphas[1] = Math.Round(start + (end - start) / 3).ToString();
                            //alphas[2] = Math.Round(start + (end - start) / 3 * 2).ToString();
                            //alphas[3] = Math.Round(start + (end - start) / 3 * 3).ToString();
                            alphas[nElems - 1] = end.ToString();
                        }

                        for (int i = 0; i < nElems * cbElem; i += cbElem)
                        {
                            colorval = Utils.getRGBColorFromOfficeArtCOLORREF(System.BitConverter.ToUInt32(colors, 6 + i), slide, so);
                            _writer.WriteStartElement("a", "gs", OpenXmlNamespaces.DrawingML);
                            _writer.WriteAttributeString("pos", positions[i / cbElem]);

                            _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                            _writer.WriteAttributeString("val", colorval);
                            if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillOpacity) && so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op != 65536)
                            {
                                _writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
                                _writer.WriteAttributeString("val", alphas[i / cbElem]);     //we need the percentage of the opacity (65536 means 100%)
                                _writer.WriteEndElement();
                            }
                            _writer.WriteEndElement();

                            _writer.WriteEndElement();
                        }
                    }
                }

                if (useFillAndBack)
                {
                    colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillColor].op, slide, so);

                    _writer.WriteStartElement("a", "gs", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("pos", "0");
                    _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", colorval);
                    if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillOpacity) && so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op != 65536)
                    {
                        _writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("val", Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op / 65536 * 100000)).ToString());     //we need the percentage of the opacity (65536 means 100%)
                        _writer.WriteEndElement();
                    }
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();

                    if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBackColor))
                    {
                        colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillBackColor].op, slide, so);
                    }
                    else
                    {
                        if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowColor))
                        {
                            colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.shadowColor].op, slide, so);
                        }
                        else
                        {
                            //use filColor
                        }
                    }

                    _writer.WriteStartElement("a", "gs", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("pos", "100000");
                    _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", colorval);
                    if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBackOpacity) && so.OptionsByID[ShapeOptions.PropertyId.fillBackOpacity].op != 65536)
                    {
                        _writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("val", Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillBackOpacity].op / 65536 * 100000)).ToString());     //we need the percentage of the opacity (65536 means 100%)
                        _writer.WriteEndElement();
                    }
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();
                }

                _writer.WriteEndElement();     //gsLst

                switch (fillType)
                {
                case 0x5:
                case 0x6:
                    _writer.WriteStartElement("a", "path", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("path", "shape");
                    _writer.WriteStartElement("a", "fillToRect", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("l", "50000");
                    _writer.WriteAttributeString("t", "50000");
                    _writer.WriteAttributeString("r", "50000");
                    _writer.WriteAttributeString("b", "50000");
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();         //path
                    break;

                default:
                    _writer.WriteStartElement("a", "path", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("path", "rect");
                    _writer.WriteStartElement("a", "fillToRect", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("r", "100000");
                    _writer.WriteAttributeString("b", "100000");
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();         //path
                    break;
                }

                _writer.WriteEndElement();     //gradFill

                break;

            case 0x7:     //shadescale
                _writer.WriteStartElement("a", "gradFill", OpenXmlNamespaces.DrawingML);
                _writer.WriteAttributeString("rotWithShape", "1");
                _writer.WriteStartElement("a", "gsLst", OpenXmlNamespaces.DrawingML);

                decimal angle        = 90;
                bool    switchColors = false;
                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillAngle))
                {
                    if (so.OptionsByID[ShapeOptions.PropertyId.fillAngle].op != 0)
                    {
                        byte[]  bytes      = BitConverter.GetBytes(so.OptionsByID[ShapeOptions.PropertyId.fillAngle].op);
                        int     integral   = BitConverter.ToInt16(bytes, 0);
                        uint    fractional = BitConverter.ToUInt16(bytes, 2);
                        Decimal result     = integral + ((decimal)fractional / (decimal)65536);
                        angle = 65536 - fractional;     //I have no idea why this works!!
                        angle = angle - 90;
                        if (angle < 0)
                        {
                            angle       += 360;
                            switchColors = true;
                        }
                    }
                }

                Dictionary <int, string> shadeColorsDic = new Dictionary <int, string>();
                List <string>            shadeColors    = new List <string>();
                if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillShadeColors) && so.OptionsByID[ShapeOptions.PropertyId.fillShadeColors].opComplex != null && so.OptionsByID[ShapeOptions.PropertyId.fillShadeColors].opComplex.Length > 0)
                {
                    uint length = so.OptionsByID[ShapeOptions.PropertyId.fillShadeColors].op;

                    //An IMsoArray record that specifies colors and their relative positions.
                    //Each element of the array contains an OfficeArtCOLORREF record color and a FixedPoint, as specified in [MS-OSHARED]
                    //section 2.2.1.6, that specifies its relative position along the gradient vector.
                    byte[] data = so.OptionsByID[ShapeOptions.PropertyId.fillShadeColors].opComplex;

                    int              pos = 0;
                    string           colval;
                    FixedPointNumber fixedpoint;
                    UInt16           nElems = BitConverter.ToUInt16(data, pos);
                    pos += 2;
                    UInt16 nElemsAlloc = BitConverter.ToUInt16(data, pos);
                    pos += 2;
                    UInt16 cbElem = BitConverter.ToUInt16(data, pos);
                    pos += 2;

                    if (cbElem == 0xFFF0)
                    {
                        //If this value is 0xFFF0 then this record is an array of truncated 8 byte elements. Only the 4 low-order bytes are recorded. Each element's 4 high-order bytes equal 0x00000000 and each element's 4 low-order bytes are contained in data.
                    }
                    else
                    {
                        while (pos < length)
                        {
                            colval = Utils.getRGBColorFromOfficeArtCOLORREF(BitConverter.ToUInt32(data, pos), slide, so);

                            pos       += 4;
                            fixedpoint = new FixedPointNumber(BitConverter.ToUInt16(data, pos), BitConverter.ToUInt16(data, pos + 2));
                            shadeColors.Insert(0, colval);
                            pos += 4;
                        }
                    }
                }
                else
                {
                    bool switchcolors = false;
                    if (switchColors & so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBackColor))
                    {
                        colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillBackColor].op, slide, so);
                    }
                    else
                    {
                        if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillColor))
                        {
                            colorval = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillColor].op, slide, so);
                        }
                        else
                        {
                            colorval     = "FFFFFF"; //TODO: find out which color to use in this case
                            switchcolors = true;
                        }
                    }

                    if (switchColors | !so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBackColor))
                    {
                        colorval2 = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillColor].op, slide, so);
                    }
                    else
                    {
                        colorval2 = Utils.getRGBColorFromOfficeArtCOLORREF(so.OptionsByID[ShapeOptions.PropertyId.fillBackColor].op, slide, so);
                    }

                    if (switchcolors)
                    {
                        //this is a workaround for a bug. Further analysis necessarry
                        string dummy = colorval;
                        colorval  = colorval2;
                        colorval2 = dummy;
                    }

                    shadeColors.Add(colorval);
                    shadeColors.Add(colorval2);
                }


                int    gspos;
                string col;
                for (int i = 0; i < shadeColors.Count; i++)
                {
                    col = shadeColors[i];
                    if (i == 0)
                    {
                        gspos = 0;
                    }
                    else if (i == shadeColors.Count - 1)
                    {
                        gspos = 100000;
                    }
                    else
                    {
                        gspos = i * 100000 / shadeColors.Count;
                    }

                    _writer.WriteStartElement("a", "gs", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("pos", gspos.ToString());
                    _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", col);
                    if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillOpacity) && so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op != 65536)
                    {
                        _writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("val", Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillOpacity].op / 65536 * 100000)).ToString());     //we need the percentage of the opacity (65536 means 100%)
                        _writer.WriteEndElement();
                    }

                    if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillShadeType))
                    {
                        uint flags    = so.OptionsByID[ShapeOptions.PropertyId.fillShadeType].op;
                        bool none     = Tools.Utils.BitmaskToBool(flags, 0x1);
                        bool gamma    = Tools.Utils.BitmaskToBool(flags, 0x1 << 1);
                        bool sigma    = Tools.Utils.BitmaskToBool(flags, 0x1 << 2);
                        bool band     = Tools.Utils.BitmaskToBool(flags, 0x1 << 3);
                        bool onecolor = Tools.Utils.BitmaskToBool(flags, 0x1 << 4);

                        if (gamma)
                        {
                            _writer.WriteElementString("a", "gamma", OpenXmlNamespaces.DrawingML, "");
                        }
                        if (band)
                        {
                            _writer.WriteStartElement("a", "shade", OpenXmlNamespaces.DrawingML);
                            _writer.WriteAttributeString("val", "37255");
                            _writer.WriteEndElement();
                        }
                        if (gamma)
                        {
                            _writer.WriteElementString("a", "invGamma", OpenXmlNamespaces.DrawingML, "");
                        }
                    }
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();
                }



                ////new colorval
                //_writer.WriteStartElement("a", "gs", OpenXmlNamespaces.DrawingML);
                //_writer.WriteAttributeString("pos", "100000");
                //_writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                //_writer.WriteAttributeString("val", colorval2);
                //if (so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.fillBackOpacity))
                //{
                //    _writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
                //    _writer.WriteAttributeString("val", Math.Round(((decimal)so.OptionsByID[ShapeOptions.PropertyId.fillBackOpacity].op / 65536 * 100000)).ToString()); //we need the percentage of the opacity (65536 means 100%)
                //    _writer.WriteEndElement();
                //}

                //_writer.WriteEndElement();
                //_writer.WriteEndElement();

                _writer.WriteEndElement();     //gsLst

                _writer.WriteStartElement("a", "lin", OpenXmlNamespaces.DrawingML);

                angle *= 60000;
                //if (angle > 5400000) angle = 5400000;

                _writer.WriteAttributeString("ang", angle.ToString());
                _writer.WriteAttributeString("scaled", "1");
                _writer.WriteEndElement();

                _writer.WriteEndElement();
                break;

            case 0x8:     //shadetitle
            case 0x9:     //background
                break;
            }
        }
        /// <summary>
        /// The overload apply method
        /// Creates the Workbook xml document
        /// </summary>
        /// <param name="bsd">WorkSheetData</param>
        public void Apply(SupBookData sbd)
        {
            Uri uri = new Uri(sbd.VirtPath, UriKind.RelativeOrAbsolute);
            ExternalRelationship er = this.xlsContext.SpreadDoc.WorkbookPart.GetExternalLinkPart().AddExternalRelationship(OpenXmlRelationshipTypes.ExternalLinkPath, uri);



            _writer.WriteStartDocument();
            _writer.WriteStartElement("externalLink", OpenXmlNamespaces.SpreadsheetML);

            _writer.WriteStartElement("externalBook");
            _writer.WriteAttributeString("r", "id", OpenXmlNamespaces.Relationships, er.Id.ToString());

            _writer.WriteStartElement("sheetNames");
            foreach (String var in sbd.RGST)
            {
                _writer.WriteStartElement("sheetName");
                _writer.WriteAttributeString("val", var);
                _writer.WriteEndElement();
            }
            _writer.WriteEndElement();

            // checks if some externNames exist
            if (sbd.ExternNames.Count > 0)
            {
                _writer.WriteStartElement("definedNames");
                foreach (String var in sbd.ExternNames)
                {
                    _writer.WriteStartElement("definedName");
                    _writer.WriteAttributeString("name", var);
                    _writer.WriteEndElement();
                }
                _writer.WriteEndElement();
            }

            if (sbd.XCTDataList.Count > 0)
            {
                _writer.WriteStartElement("sheetDataSet");
                int counter = 0;
                foreach (XCTData var in sbd.XCTDataList)
                {
                    _writer.WriteStartElement("sheetData");
                    _writer.WriteAttributeString("sheetId", counter.ToString());
                    counter++;
                    foreach (CRNData crn in var.CRNDataList)
                    {
                        _writer.WriteStartElement("row");
                        _writer.WriteAttributeString("r", (crn.rw + 1).ToString());
                        for (byte i = crn.colFirst; i <= crn.colLast; i++)
                        {
                            _writer.WriteStartElement("cell");
                            _writer.WriteAttributeString("r", ExcelHelperClass.intToABCString((int)i, (crn.rw + 1).ToString()));
                            if (crn.oper[i - crn.colFirst] is bool)
                            {
                                _writer.WriteAttributeString("t", "b");
                                if ((bool)crn.oper[i - crn.colFirst])
                                {
                                    _writer.WriteElementString("v", "1");
                                }
                                else
                                {
                                    _writer.WriteElementString("v", "0");
                                }
                            }
                            if (crn.oper[i - crn.colFirst] is double)
                            {
                                // _writer.WriteAttributeString("t", "b");
                                _writer.WriteElementString("v", Convert.ToString(crn.oper[i - crn.colFirst], CultureInfo.GetCultureInfo("en-US")));
                            }
                            if (crn.oper[i - crn.colFirst] is String)
                            {
                                _writer.WriteAttributeString("t", "str");
                                _writer.WriteElementString("v", crn.oper[i - crn.colFirst].ToString());
                            }


                            _writer.WriteEndElement();
                        }

                        _writer.WriteEndElement();
                    }

                    _writer.WriteEndElement();
                }
                _writer.WriteEndElement();
            }

            _writer.WriteEndElement();
            _writer.WriteEndElement();      // close worksheet
            _writer.WriteEndDocument();



            sbd.ExternalLinkId  = this.xlsContext.SpreadDoc.WorkbookPart.GetExternalLinkPart().RelId;
            sbd.ExternalLinkRef = this.xlsContext.SpreadDoc.WorkbookPart.GetExternalLinkPart().RelIdToString;

            // close writer
            _writer.Flush();
        }
Exemple #7
0
        /// <summary>
        /// The overload apply method
        /// Creates the Worksheet xml document
        /// </summary>
        /// <param name="bsd">WorkSheetData</param>
        public void Apply(WorkSheetData bsd)
        {
            _xlsContext.CurrentSheet = bsd;
            _writer.WriteStartDocument();
            _writer.WriteStartElement("worksheet", OpenXmlNamespaces.SpreadsheetML);
            //if (bsd.emtpyWorksheet)
            //{
            //    _writer.WriteStartElement("sheetData");
            //    _writer.WriteEndElement();
            //}
            //else
            {
                // default info
                if (bsd.defaultColWidth >= 0 || bsd.defaultRowHeight >= 0)
                {
                    _writer.WriteStartElement("sheetFormatPr");

                    if (bsd.defaultColWidth >= 0)
                    {
                        double colWidht = (double)bsd.defaultColWidth;
                        _writer.WriteAttributeString("defaultColWidth", Convert.ToString(colWidht, CultureInfo.GetCultureInfo("en-US")));
                    }
                    if (bsd.defaultRowHeight >= 0)
                    {
                        TwipsValue tv = new TwipsValue(bsd.defaultRowHeight);
                        _writer.WriteAttributeString("defaultRowHeight", Convert.ToString(tv.ToPoints(), CultureInfo.GetCultureInfo("en-US")));
                    }
                    if (bsd.zeroHeight)
                    {
                        _writer.WriteAttributeString("zeroHeight", "1");
                    }
                    if (bsd.customHeight)
                    {
                        _writer.WriteAttributeString("customHeight", "1");
                    }
                    if (bsd.thickTop)
                    {
                        _writer.WriteAttributeString("thickTop", "1");
                    }
                    if (bsd.thickBottom)
                    {
                        _writer.WriteAttributeString("thickBottom", "1");
                    }

                    _writer.WriteEndElement(); // sheetFormatPr
                }



                // Col info
                if (bsd.colInfoDataTable.Count > 0)
                {
                    _writer.WriteStartElement("cols");
                    foreach (ColumnInfoData col in bsd.colInfoDataTable)
                    {
                        _writer.WriteStartElement("col");
                        // write min and max
                        // booth values are 0 based in the binary format and 1 based in the oxml format
                        // so you have to add 1 to the value!

                        _writer.WriteAttributeString("min", (col.min + 1).ToString());
                        _writer.WriteAttributeString("max", (col.max + 1).ToString());

                        if (col.widht != 0)
                        {
                            double colWidht = (double)col.widht / 256;
                            _writer.WriteAttributeString("width", Convert.ToString(colWidht, CultureInfo.GetCultureInfo("en-US")));
                        }
                        if (col.hidden)
                        {
                            _writer.WriteAttributeString("hidden", "1");
                        }

                        if (col.outlineLevel > 0)
                        {
                            _writer.WriteAttributeString("outlineLevel", col.outlineLevel.ToString());
                        }

                        if (col.customWidth)
                        {
                            _writer.WriteAttributeString("customWidth", "1");
                        }


                        if (col.bestFit)
                        {
                            _writer.WriteAttributeString("bestFit", "1");
                        }

                        if (col.phonetic)
                        {
                            _writer.WriteAttributeString("phonetic", "1");
                        }

                        if (col.style > 15)
                        {
                            _writer.WriteAttributeString("style", Convert.ToString(col.style - this._xlsContext.XlsDoc.WorkBookData.styleData.XFCellStyleDataList.Count, CultureInfo.GetCultureInfo("en-US")));
                        }

                        _writer.WriteEndElement(); // col
                    }


                    _writer.WriteEndElement();
                }
                // End col info

                _writer.WriteStartElement("sheetData");
                //  bsd.rowDataTable.Values
                foreach (RowData row in bsd.rowDataTable.Values)
                {
                    // write row start tag
                    // Row
                    _writer.WriteStartElement("row");
                    // the rowindex from the binary format is zero based, the ooxml format is one based
                    _writer.WriteAttributeString("r", (row.Row + 1).ToString());
                    if (row.height != null)
                    {
                        _writer.WriteAttributeString("ht", Convert.ToString(row.height.ToPoints(), CultureInfo.GetCultureInfo("en-US")));
                        if (row.customHeight)
                        {
                            _writer.WriteAttributeString("customHeight", "1");
                        }
                    }

                    if (row.hidden)
                    {
                        _writer.WriteAttributeString("hidden", "1");
                    }
                    if (row.outlineLevel > 0)
                    {
                        _writer.WriteAttributeString("outlineLevel", row.outlineLevel.ToString());
                    }
                    if (row.collapsed)
                    {
                        _writer.WriteAttributeString("collapsed", "1");
                    }
                    if (row.customFormat)
                    {
                        _writer.WriteAttributeString("customFormat", "1");
                        if (row.style > 15)
                        {
                            _writer.WriteAttributeString("s", (row.style - this._xlsContext.XlsDoc.WorkBookData.styleData.XFCellStyleDataList.Count).ToString());
                        }
                    }
                    if (row.thickBot)
                    {
                        _writer.WriteAttributeString("thickBot", "1");
                    }
                    if (row.thickTop)
                    {
                        _writer.WriteAttributeString("thickTop", "1");
                    }
                    if (row.minSpan + 1 > 0 && row.maxSpan > 0 && row.minSpan + 1 < row.maxSpan)
                    {
                        _writer.WriteAttributeString("spans", (row.minSpan + 1).ToString() + ":" + row.maxSpan.ToString());
                    }

                    row.Cells.Sort();
                    foreach (AbstractCellData cell in row.Cells)
                    {
                        // Col
                        _writer.WriteStartElement("c");
                        _writer.WriteAttributeString("r", ExcelHelperClass.intToABCString((int)cell.Col, (cell.Row + 1).ToString()));

                        if (cell.TemplateID > 15)
                        {
                            _writer.WriteAttributeString("s", (cell.TemplateID - this._xlsContext.XlsDoc.WorkBookData.styleData.XFCellStyleDataList.Count).ToString());
                        }

                        if (cell is StringCell)
                        {
                            _writer.WriteAttributeString("t", "s");
                        }
                        if (cell is FormulaCell)
                        {
                            FormulaCell fcell = (FormulaCell)cell;


                            if (((FormulaCell)cell).calculatedValue is String)
                            {
                                _writer.WriteAttributeString("t", "str");
                            }
                            else if (((FormulaCell)cell).calculatedValue is double)
                            {
                                _writer.WriteAttributeString("t", "n");
                            }
                            else if (((FormulaCell)cell).calculatedValue is byte)
                            {
                                _writer.WriteAttributeString("t", "b");
                            }
                            else if (((FormulaCell)cell).calculatedValue is int)
                            {
                                _writer.WriteAttributeString("t", "e");
                            }


                            // <f>1</f>
                            _writer.WriteStartElement("f");
                            if (!fcell.isSharedFormula)
                            {
                                String value = FormulaInfixMapping.mapFormula(fcell.PtgStack, this._xlsContext);


                                if (fcell.usesArrayRecord)
                                {
                                    _writer.WriteAttributeString("t", "array");
                                    _writer.WriteAttributeString("ref", ExcelHelperClass.intToABCString((int)cell.Col, (cell.Row + 1).ToString()));
                                }
                                if (fcell.alwaysCalculated)
                                {
                                    _writer.WriteAttributeString("ca", "1");
                                }

                                if (value.Equals(""))
                                {
                                    TraceLogger.Debug("Formula Parse Error in Row {0}\t Column {1}\t", cell.Row.ToString(), cell.Col.ToString());
                                }

                                _writer.WriteString(value);
                            }
                            /// If this cell is part of a shared formula
                            ///
                            else
                            {
                                SharedFormulaData sfd = bsd.checkFormulaIsInShared(cell.Row, cell.Col);
                                if (sfd != null)
                                {
                                    // t="shared"
                                    _writer.WriteAttributeString("t", "shared");
                                    //  <f t="shared" ref="C4:C11" si="0">H4+I4-J4</f>
                                    _writer.WriteAttributeString("si", sfd.ID.ToString());
                                    if (sfd.RefCount == 0)
                                    {
                                        /// Write value and reference
                                        _writer.WriteAttributeString("ref", sfd.getOXMLFormatedData());

                                        String value = FormulaInfixMapping.mapFormula(sfd.PtgStack, this._xlsContext, sfd.rwFirst, sfd.colFirst);
                                        _writer.WriteString(value);

                                        sfd.RefCount++;
                                    }
                                }
                                else
                                {
                                    TraceLogger.Debug("Formula Parse Error in Row {0}\t Column {1}\t", cell.Row.ToString(), cell.Col.ToString());
                                }
                            }

                            _writer.WriteEndElement();
                            /// write down calculated value from a formula
                            ///

                            _writer.WriteStartElement("v");

                            if (((FormulaCell)cell).calculatedValue is int)
                            {
                                _writer.WriteString(FormulaInfixMapping.getErrorStringfromCode((int)((FormulaCell)cell).calculatedValue));
                            }
                            else
                            {
                                _writer.WriteString(Convert.ToString(((FormulaCell)cell).calculatedValue, CultureInfo.GetCultureInfo("en-US")));
                            }

                            _writer.WriteEndElement();
                        }
                        else
                        {// Data !!!
                            _writer.WriteElementString("v", cell.getValue());
                        }
                        // add a type to the c element if the formula returns following types

                        _writer.WriteEndElement();  // close cell (c)
                    }


                    _writer.WriteEndElement();  // close row
                }

                // close tags
                _writer.WriteEndElement();      // close sheetData


                // Add the mergecell part
                //
                // - <mergeCells count="2">
                //        <mergeCell ref="B3:C3" />
                //        <mergeCell ref="E3:F4" />
                //     </mergeCells>
                if (bsd.MERGECELLSData != null)
                {
                    _writer.WriteStartElement("mergeCells");
                    _writer.WriteAttributeString("count", bsd.MERGECELLSData.cmcs.ToString());
                    foreach (MergeCellData mcell in bsd.MERGECELLSData.mergeCellDataList)
                    {
                        _writer.WriteStartElement("mergeCell");
                        _writer.WriteAttributeString("ref", mcell.getOXMLFormatedData());
                        _writer.WriteEndElement();
                    }
                    // close mergeCells Tag
                    _writer.WriteEndElement();
                }

                // hyperlinks!

                if (bsd.HyperLinkList.Count != 0)
                {
                    _writer.WriteStartElement("hyperlinks");
                    bool writtenParentElement = false;
                    foreach (HyperlinkData link in bsd.HyperLinkList)
                    {
                        //    Uri url;
                        //    if (link.absolute)
                        //    {

                        //        if (link.url.StartsWith("http", true, CultureInfo.GetCultureInfo("en-US"))
                        //            || link.url.StartsWith("mailto", true, CultureInfo.GetCultureInfo("en-US")))
                        //        {
                        //            url = new Uri(link.url, UriKind.Absolute);

                        //        }
                        //        else
                        //        {
                        //            link.url = "file:///" + link.url;
                        //            url = new Uri(link.url, UriKind.Absolute);
                        //        }

                        //    }
                        //    else
                        //    {

                        //        url = new Uri(link.url, UriKind.Relative);

                        //    }
                        //    try
                        //    {
                        //        if (System.Uri.IsWellFormedUriString(url.LocalPath.ToString(), System.UriKind.Absolute))
                        //        {

                        //if (!writtenParentElement)
                        //{

                        //    writtenParentElement = true;
                        //}
                        string refstring;

                        if (link.colLast == link.colFirst && link.rwLast == link.rwFirst)
                        {
                            refstring = ExcelHelperClass.intToABCString((int)link.colLast, (link.rwLast + 1).ToString());
                        }
                        else
                        {
                            refstring = ExcelHelperClass.intToABCString((int)link.colFirst, (link.rwFirst + 1).ToString()) + ":" + ExcelHelperClass.intToABCString((int)link.colLast, (link.rwLast + 1).ToString());
                        }

                        if (link.url != null)
                        {
                            ExternalRelationship er = this._xlsContext.SpreadDoc.WorkbookPart.GetWorksheetPart().AddExternalRelationship(OpenXmlRelationshipTypes.HyperLink, link.url.Replace(" ", ""));

                            _writer.WriteStartElement("hyperlink");
                            _writer.WriteAttributeString("ref", refstring);
                            _writer.WriteAttributeString("r", "id", OpenXmlNamespaces.Relationships, er.Id.ToString());

                            _writer.WriteEndElement();
                        }
                        else if (link.location != null)
                        {
                            _writer.WriteStartElement("hyperlink");
                            _writer.WriteAttributeString("ref", refstring);
                            _writer.WriteAttributeString("location", link.location);
                            if (link.display != null)
                            {
                                _writer.WriteAttributeString("display", link.display);
                            }
                            _writer.WriteEndElement();
                        }

                        /*           }
                         * }
                         *  catch (Exception ex)
                         *  {
                         *      TraceLogger.DebugInternal(ex.Message.ToString());
                         *      TraceLogger.DebugInternal(ex.StackTrace.ToString());
                         *  }
                         * }*/
                    }
                    _writer.WriteEndElement(); // hyperlinks
                    if (writtenParentElement)
                    {
                    }
                }

                // worksheet margins !!
                if (bsd.leftMargin != null && bsd.topMargin != null &&
                    bsd.rightMargin != null && bsd.bottomMargin != null &&
                    bsd.headerMargin != null && bsd.footerMargin != null)
                {
                    _writer.WriteStartElement("pageMargins");
                    {
                        _writer.WriteAttributeString("left", Convert.ToString(bsd.leftMargin, CultureInfo.GetCultureInfo("en-US")));
                        _writer.WriteAttributeString("right", Convert.ToString(bsd.rightMargin, CultureInfo.GetCultureInfo("en-US")));
                        _writer.WriteAttributeString("top", Convert.ToString(bsd.topMargin, CultureInfo.GetCultureInfo("en-US")));
                        _writer.WriteAttributeString("bottom", Convert.ToString(bsd.bottomMargin, CultureInfo.GetCultureInfo("en-US")));
                        _writer.WriteAttributeString("header", Convert.ToString(bsd.headerMargin, CultureInfo.GetCultureInfo("en-US")));
                        _writer.WriteAttributeString("footer", Convert.ToString(bsd.footerMargin, CultureInfo.GetCultureInfo("en-US")));
                    }
                    _writer.WriteEndElement(); // pageMargins
                }

                // page setup settings
                if (bsd.PageSetup != null)
                {
                    _writer.WriteStartElement("pageSetup");

                    if (!bsd.PageSetup.fNoPls && bsd.PageSetup.iPaperSize > 0 && bsd.PageSetup.iPaperSize < 255)
                    {
                        _writer.WriteAttributeString("paperSize", bsd.PageSetup.iPaperSize.ToString());
                    }
                    if (bsd.PageSetup.iScale >= 10 && bsd.PageSetup.iScale <= 400)
                    {
                        _writer.WriteAttributeString("scale", bsd.PageSetup.iScale.ToString());
                    }
                    _writer.WriteAttributeString("firstPageNumber", bsd.PageSetup.iPageStart.ToString());
                    _writer.WriteAttributeString("fitToWidth", bsd.PageSetup.iFitWidth.ToString());
                    _writer.WriteAttributeString("fitToHeight", bsd.PageSetup.iFitHeight.ToString());

                    if (bsd.PageSetup.fLeftToRight)
                    {
                        _writer.WriteAttributeString("pageOrder", "overThenDown");
                    }

                    if (!bsd.PageSetup.fNoOrient)
                    {
                        if (bsd.PageSetup.fPortrait)
                        {
                            _writer.WriteAttributeString("orientation", "portrait");
                        }
                        else
                        {
                            _writer.WriteAttributeString("orientation", "landscape");
                        }
                    }

                    //10 <attribute name="usePrinterDefaults" type="xsd:boolean" use="optional" default="true"/>

                    if (bsd.PageSetup.fNoColor)
                    {
                        _writer.WriteAttributeString("blackAndWhite", "1");
                    }
                    if (bsd.PageSetup.fDraft)
                    {
                        _writer.WriteAttributeString("draft", "1");
                    }

                    if (bsd.PageSetup.fNotes)
                    {
                        if (bsd.PageSetup.fEndNotes)
                        {
                            _writer.WriteAttributeString("cellComments", "atEnd");
                        }
                        else
                        {
                            _writer.WriteAttributeString("cellComments", "asDisplayed");
                        }
                    }
                    if (bsd.PageSetup.fUsePage)
                    {
                        _writer.WriteAttributeString("useFirstPageNumber", "1");
                    }

                    switch (bsd.PageSetup.iErrors)
                    {
                    case 0x00: _writer.WriteAttributeString("errors", "displayed"); break;

                    case 0x01: _writer.WriteAttributeString("errors", "blank"); break;

                    case 0x02: _writer.WriteAttributeString("errors", "dash"); break;

                    case 0x03: _writer.WriteAttributeString("errors", "NA"); break;

                    default: _writer.WriteAttributeString("errors", "displayed"); break;
                    }

                    _writer.WriteAttributeString("horizontalDpi", bsd.PageSetup.iRes.ToString());
                    _writer.WriteAttributeString("verticalDpi", bsd.PageSetup.iVRes.ToString());
                    if (!bsd.PageSetup.fNoPls)
                    {
                        _writer.WriteAttributeString("copies", bsd.PageSetup.iCopies.ToString());
                    }

                    _writer.WriteEndElement();
                }

                // embedded drawings (charts etc)
                if (bsd.ObjectsSequence != null)
                {
                    _writer.WriteStartElement(Sml.Sheet.ElDrawing, Sml.Ns);
                    {
                        _writer.WriteAttributeString("r", "id", OpenXmlNamespaces.Relationships, this._worksheetPart.DrawingsPart.RelIdToString);
                        bsd.ObjectsSequence.Convert(new DrawingMapping(this._xlsContext, this._worksheetPart.DrawingsPart, false));
                    }
                    _writer.WriteEndElement();
                }
            }

            _writer.WriteEndElement();      // close worksheet
            _writer.WriteEndDocument();

            // close writer
            _writer.Flush();
        }
        // prohibit
        // - altChunk
        // - subDoc
        // - contentPart

        // This strips all text nodes from the XML tree, thereby leaving only the structure.

        private static object CloneBlockLevelContentForHashing(
            OpenXmlPart mainDocumentPart,
            XNode node,
            bool includeRelatedParts,
            WmlComparerSettings settings)
        {
            if (node is XElement element)
            {
                if (element.Name == W.bookmarkStart ||
                    element.Name == W.bookmarkEnd ||
                    element.Name == W.pPr ||
                    element.Name == W.rPr)
                {
                    return(null);
                }

                if (element.Name == W.p)
                {
                    var clonedPara = new XElement(element.Name,
                                                  element.Attributes().Where(a => a.Name != W.rsid &&
                                                                             a.Name != W.rsidDel &&
                                                                             a.Name != W.rsidP &&
                                                                             a.Name != W.rsidR &&
                                                                             a.Name != W.rsidRDefault &&
                                                                             a.Name != W.rsidRPr &&
                                                                             a.Name != W.rsidSect &&
                                                                             a.Name != W.rsidTr &&
                                                                             a.Name.Namespace != PtOpenXml.pt),
                                                  element.Nodes().Select(n =>
                                                                         CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));

                    IEnumerable <IGrouping <bool, XElement> > groupedRuns = clonedPara
                                                                            .Elements()
                                                                            .GroupAdjacent(e => e.Name == W.r &&
                                                                                           e.Elements().Count() == 1 &&
                                                                                           e.Element(W.t) != null);

                    var clonedParaWithGroupedRuns = new XElement(element.Name,
                                                                 groupedRuns.Select(g =>
                    {
                        if (g.Key)
                        {
                            string text = g.Select(t => t.Value).StringConcatenate();
                            if (settings.CaseInsensitive)
                            {
                                text = text.ToUpper(settings.CultureInfo);
                            }
                            var newRun = (object)new XElement(W.r,
                                                              new XElement(W.t,
                                                                           text));
                            return(newRun);
                        }

                        return(g);
                    }));

                    return(clonedParaWithGroupedRuns);
                }

                if (element.Name == W.r)
                {
                    IEnumerable <XElement> clonedRuns = element
                                                        .Elements()
                                                        .Where(e => e.Name != W.rPr)
                                                        .Select(rc => new XElement(W.r,
                                                                                   CloneBlockLevelContentForHashing(mainDocumentPart, rc, includeRelatedParts, settings)));
                    return(clonedRuns);
                }

                if (element.Name == W.tbl)
                {
                    var clonedTable = new XElement(W.tbl,
                                                   element.Elements(W.tr).Select(n =>
                                                                                 CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
                    return(clonedTable);
                }

                if (element.Name == W.tr)
                {
                    var clonedRow = new XElement(W.tr,
                                                 element.Elements(W.tc).Select(n =>
                                                                               CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
                    return(clonedRow);
                }

                if (element.Name == W.tc)
                {
                    var clonedCell = new XElement(W.tc,
                                                  element.Elements().Select(n =>
                                                                            CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
                    return(clonedCell);
                }

                if (element.Name == W.tcPr)
                {
                    var clonedCellProps = new XElement(W.tcPr,
                                                       element.Elements(W.gridSpan).Select(n =>
                                                                                           CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
                    return(clonedCellProps);
                }

                if (element.Name == W.gridSpan)
                {
                    var clonedGridSpan = new XElement(W.gridSpan,
                                                      new XAttribute("val", (string)element.Attribute(W.val)));
                    return(clonedGridSpan);
                }

                if (element.Name == W.txbxContent)
                {
                    var clonedTextbox = new XElement(W.txbxContent,
                                                     element.Elements().Select(n =>
                                                                               CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
                    return(clonedTextbox);
                }

                if (includeRelatedParts)
                {
                    if (ComparisonUnitWord.ElementsWithRelationshipIds.Contains(element.Name))
                    {
                        var newElement = new XElement(element.Name,
                                                      element.Attributes()
                                                      .Where(a => a.Name.Namespace != PtOpenXml.pt)
                                                      .Where(a => !AttributesToTrimWhenCloning.Contains(a.Name))
                                                      .Select(a =>
                        {
                            if (!ComparisonUnitWord.RelationshipAttributeNames.Contains(a.Name))
                            {
                                return(a);
                            }

                            var rId = (string)a;

                            // could be an hyperlink relationship
                            try
                            {
                                OpenXmlPart oxp = mainDocumentPart.GetPartById(rId);
                                if (oxp == null)
                                {
                                    throw new FileFormatException("Invalid WordprocessingML Document");
                                }

                                var anno = oxp.Annotation <PartSHA1HashAnnotation>();
                                if (anno != null)
                                {
                                    return(new XAttribute(a.Name, anno.Hash));
                                }

                                if (!oxp.ContentType.EndsWith("xml"))
                                {
                                    using (Stream str = oxp.GetStream())
                                    {
                                        byte[] ba;
                                        using (var br = new BinaryReader(str))
                                        {
                                            ba = br.ReadBytes((int)str.Length);
                                        }

                                        string sha1 = WmlComparerUtil.SHA1HashStringForByteArray(ba);
                                        oxp.AddAnnotation(new PartSHA1HashAnnotation(sha1));
                                        return(new XAttribute(a.Name, sha1));
                                    }
                                }
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                HyperlinkRelationship hr =
                                    mainDocumentPart.HyperlinkRelationships.FirstOrDefault(z => z.Id == rId);
                                if (hr != null)
                                {
                                    string str = hr.Uri.ToString();
                                    return(new XAttribute(a.Name, str));
                                }

                                // could be an external relationship
                                ExternalRelationship er =
                                    mainDocumentPart.ExternalRelationships.FirstOrDefault(z => z.Id == rId);
                                if (er != null)
                                {
                                    string str = er.Uri.ToString();
                                    return(new XAttribute(a.Name, str));
                                }

                                return(new XAttribute(a.Name, "NULL Relationship"));
                            }

                            return(null);
                        }),
                                                      element.Nodes().Select(n =>
                                                                             CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
                        return(newElement);
                    }
                }

                if (element.Name == VML.shape)
                {
                    return(new XElement(element.Name,
                                        element.Attributes()
                                        .Where(a => a.Name.Namespace != PtOpenXml.pt)
                                        .Where(a => a.Name != "style" && a.Name != "id" && a.Name != "type"),
                                        element.Nodes().Select(n =>
                                                               CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings))));
                }

                if (element.Name == O.OLEObject)
                {
                    var o = new XElement(element.Name,
                                         element.Attributes()
                                         .Where(a => a.Name.Namespace != PtOpenXml.pt)
                                         .Where(a => a.Name != "ObjectID" && a.Name != R.id),
                                         element.Nodes().Select(n =>
                                                                CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
                    return(o);
                }

                if (element.Name == W._object)
                {
                    var o = new XElement(element.Name,
                                         element.Attributes()
                                         .Where(a => a.Name.Namespace != PtOpenXml.pt),
                                         element.Nodes().Select(n =>
                                                                CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)));
                    return(o);
                }

                if (element.Name == WP.docPr)
                {
                    return(new XElement(element.Name,
                                        element.Attributes()
                                        .Where(a => a.Name.Namespace != PtOpenXml.pt && a.Name != "id"),
                                        element.Nodes().Select(n =>
                                                               CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings))));
                }

                return(new XElement(element.Name,
                                    element.Attributes()
                                    .Where(a => a.Name.Namespace != PtOpenXml.pt)
                                    .Where(a => !AttributesToTrimWhenCloning.Contains(a.Name)),
                                    element.Nodes().Select(n =>
                                                           CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings))));
            }

            if (settings.CaseInsensitive)
            {
                if (node is XText xt)
                {
                    string newText = xt.Value.ToUpper(settings.CultureInfo);
                    return(new XText(newText));
                }
            }

            return(node);
        }
Exemple #9
0
        public static void LoadOpenXml(this FlowDocument doc, Stream stream)
        {
            using (WordprocessingDocument wdoc = WordprocessingDocument.Open(stream, false))
            {
                //get default style
                XDocument  xstyle, xdoc;
                StylesPart part = wdoc.MainDocumentPart.StyleDefinitionsPart;
                if (part == null)
                {
                    //part = AddStylesPartToPackage(wdoc);
                    xstyle = XDocument.Load(File.OpenRead("styles.xml"));
                }
                else
                {
                    //using (StreamReader sr = new StreamReader(part.GetStream()))
                    //{
                    xstyle = XDocument.Load(part.GetStream());
                }

                var styles = from style in xstyle
                             .Root
                             .Descendants(w_style)
                             let pPr = style
                                       .Elements(w_pPr)
                                       .FirstOrDefault()
                                       let rPr = style
                                                 .Elements(w_rPr)
                                                 .FirstOrDefault()
                                                 select new
                {
                    pStyleName = style.Attribute(w_styleId).Value,
                    pName      = style.Element(w_name).Attribute(w_val).Value,
                    pPStyle    = pPr,
                    pRStyle    = rPr
                };

                foreach (var style in styles)
                {
                    Style pStyle = style.pPStyle.ToWPFStyle();
                    pStyle.BasedOn = style.pRStyle.ToWPFStyle();

                    doc.Resources.Add(style.pStyleName, pStyle);
                }
                //}

                //get document
                using (StreamReader sr = new StreamReader(wdoc.MainDocumentPart.GetStream()))
                {
                    xdoc = XDocument.Load(sr);

                    var paragraphs = from par in xdoc
                                     .Root
                                     .Element(w_body)
                                     .Descendants(w_p)
                                     let par_style = par
                                                     .Elements(w_pPr)
                                                     .Elements(w_pStyle)
                                                     .FirstOrDefault()
                                                     let par_inline = par
                                                                      .Elements(w_pPr)
                                                                      .FirstOrDefault()
                                                                      let par_list = par
                                                                                     .Elements(w_pPr)
                                                                                     .Elements(w_numPr)
                                                                                     .FirstOrDefault()
                                                                                     select new
                    {
                        pElement = par,
                        pStyle   = par_style != null?par_style.Attribute(w_val).Value : (from d_style in xstyle
                                                                                         .Root
                                                                                         .Elements(w_style)
                                                                                             where
                                                                                         d_style.Attribute(w_type).Value == "paragraph" &&
                                                                                         d_style.Attribute(w_default).Value == "1"
                                                                                         select d_style).First().Attribute(w_styleId).Value,
                        pAttrs = par_inline,
                        pRuns  = par.Elements().Where(e => e.Name == w_r || e.Name == w_ins || e.Name == w_link || e.Name == w_numId || e.Name == w_numPr || e.Name == w_ilvl),
                        pList  = par_list
                    };


                    foreach (var par in paragraphs)
                    {
                        Paragraph p = new Paragraph();

                        Style pStyle = par.pAttrs.ToWPFStyle();
                        if (par.pStyle != string.Empty)
                        {
                            pStyle.BasedOn = doc.Resources[par.pStyle] as Style;
                        }
                        p.Style = pStyle;



                        var runs = from run in par.pRuns
                                   let run_style = run
                                                   .Elements(w_rPr)
                                                   .FirstOrDefault()
                                                   let run_istyle = run
                                                                    .Elements(w_rPr)
                                                                    .Elements(w_rStyle)
                                                                    .FirstOrDefault()
                                                                    let run_graph = run
                                                                                    .Elements(w_drawing)
                                                                                    select new
                        {
                            pRun      = run,
                            pRunType  = run.Name.LocalName,
                            pStyle    = run_istyle != null?run_istyle.Attribute(w_val).Value : string.Empty,
                            pAttrs    = run_style,
                            pText     = run.Descendants(w_t),
                            pBB       = run.Elements(w_br) != null,
                            pExRelID  = run.Name == w_link?run.Attribute(rels_id).Value : string.Empty,
                            pGraphics = run_graph
                        };

                        foreach (var run in runs)
                        {
                            Run   r      = new Run();
                            Style rStyle = run.pAttrs.ToWPFStyle();
                            if (run.pStyle != string.Empty)
                            {
                                rStyle.BasedOn = doc.Resources[run.pStyle] as Style;
                            }
                            r.Style = rStyle;

                            r.Text = run.pText.ToString(txt => txt.Value);


                            if (run.pRunType == "hyperlink")
                            {
                                ExternalRelationship er = (from rel in wdoc.MainDocumentPart.ExternalRelationships
                                                           where rel.Id == run.pExRelID
                                                           select rel).FirstOrDefault() as ExternalRelationship;
                                if (er != null)
                                {
                                    Hyperlink hl = new Hyperlink(r);
                                    hl.NavigateUri = er.Uri;
                                    p.Inlines.Add(hl);
                                }
                            }
                            else
                            {
                                p.Inlines.Add(r);
                            }


                            var graphics = from graph in run.pGraphics
                                           let pBlip = graph
                                                       .Descendants(a_blip)
                                                       .Where(x => x.Attribute(rels_embed) != null)
                                                       .FirstOrDefault()
                                                       let pExtent = graph
                                                                     .Descendants(wp_extent)
                                                                     .FirstOrDefault()
                                                                     select new
                            {
                                pWidth   = pExtent != null?pExtent.Attribute("cx").Value   : "0",
                                pHeight  = pExtent != null?pExtent.Attribute("cy").Value   : "0",
                                pExRelID = pBlip != null?pBlip.Attribute(rels_embed).Value : string.Empty
                            };
                            foreach (var graphic in graphics)
                            {
                                Console.WriteLine(graphic);
                            }
                        }

                        if (par.pList != null)
                        {
                            int      level = int.Parse(par.pList.Element(w_ilvl).Attribute(w_val).Value);
                            List     lst   = doc.Blocks.LastBlock as List;
                            ListItem nli   = new ListItem(p);
                            if (lst != null && lst.Tag != null && (int)lst.Tag < level)
                            {
                                List nlst = new List(nli);
                                nlst.Tag = level;
                                lst.ListItems.LastListItem.Blocks.Add(nlst);
                            }
                            else
                            {
                                lst     = new List(nli);
                                lst.Tag = level;
                                doc.Blocks.Add(lst);
                            }
                        }

                        else
                        {
                            doc.Blocks.Add(p);
                        }
                    }
                }
            }
        }
Exemple #10
0
        static string RenderDocument(WordprocessingDocument document)
        {
            string     s    = "";
            XNamespace w    = WordProcessingMLNamespace;
            XNamespace rels = RelationshipsNamespace;
            XNamespace a    = DrawingMLNamespace;
            XNamespace wp   = WordprocessingDrawingNamespace;

            XName w_r         = w + "r";
            XName w_ins       = w + "ins";
            XName w_hyperlink = w + "hyperlink";

            XDocument xDoc = XDocument.Load(
                XmlReader.Create(
                    new StreamReader(document.MainDocumentPart.GetStream())
                    )
                );

            string defaultStyle = GetDefaultStyleName(document);

            // Fetch paragraphs
            var paragraphs = from l_paragraph in xDoc
                             .Root
                             .Element(w + "body")
                             .Descendants(w + "p")
                             let l_paragraph_styleNode = l_paragraph
                                                         .Elements(w + "pPr")
                                                         .Elements(w + "pStyle")
                                                         .FirstOrDefault()
                                                         let l_paragraph_inlineStyleNode = l_paragraph
                                                                                           .Elements(w + "pPr")
                                                                                           .FirstOrDefault()
                                                                                           select new
            {
                ParagraphElement                = l_paragraph,
                CssClass                        = l_paragraph_styleNode != null ? ((string)l_paragraph_styleNode.Attribute(w + "val")).Replace(" ", "") : defaultStyle,
                CssStyles                       = l_paragraph_inlineStyleNode != null?CreateCssProperties(l_paragraph_inlineStyleNode.CreateReader()) : "",
                                           Runs = l_paragraph.Elements().Where(z => z.Name == w_r || z.Name == w_ins || z.Name == w_hyperlink)
            };

            // Write paragraphs
            foreach (var paragraph in paragraphs)
            {
                s += String.Format("<p class=\"{0}\" style=\"{1}\">\n", paragraph.CssClass, paragraph.CssStyles);

                // Fetch runs
                var runs = from l_run in paragraph.Runs
                           let l_run_styleNode = l_run
                                                 .Elements(w + "rPr")
                                                 .FirstOrDefault()
                                                 let l_run_inheritStyle = l_run
                                                                          .Elements(w + "rPr")
                                                                          .Elements(w + "rStyle")
                                                                          .FirstOrDefault()
                                                                          let l_run_graphics = l_run
                                                                                               .Elements(w + "drawing")
                                                                                               select new
                {
                    Run       = l_run,
                    RunType   = l_run.Name.LocalName,
                    CssStyles = l_run_styleNode != null?CreateCssProperties(l_run_styleNode.CreateReader()) : "",
                                    CssClass           = l_run_inheritStyle != null ? (string)l_run_inheritStyle.Attribute(w + "val") : "",
                                    Text               = l_run.Descendants(w + "t").StringConcatenate(element => (string)element),
                                    BreakBefore        = l_run.Element(w + "br") != null,
                                    ExternalRelationId = (l_run.Name == w_hyperlink ? (string)l_run.Attribute(rels + "id") : ""),
                                    Graphics           = l_run_graphics
                };

                // Write runs
                foreach (var run in runs)
                {
                    // Break before?
                    if (run.BreakBefore)
                    {
                        s += "<br />";
                    }

                    // Write run
                    s += String.Format("<span class=\"{0}\" style=\"{1}\">",
                                       run.CssClass,
                                       run.CssStyles ?? ""
                                       );

                    // Is it an hyperlink?
                    if (run.RunType == "hyperlink")
                    {
                        ExternalRelationship relation = (from rel in document.MainDocumentPart.ExternalRelationships
                                                         where rel.Id == run.ExternalRelationId
                                                         select rel).FirstOrDefault() as ExternalRelationship;
                        if (relation != null)
                        {
                            s += "<a href=\"" + relation.Uri.ToString() + "\">";
                        }
                    }

                    // Fetch graphics
                    var graphics = from l_graphic in run.Graphics
                                   let l_graphic_blip = l_graphic
                                                        .Descendants(a + "blip")
                                                        .Where(x => x.Attribute(rels + "embed") != null)
                                                        .FirstOrDefault()
                                                        let l_graphic_extent = l_graphic
                                                                               .Descendants(wp + "extent")
                                                                               .FirstOrDefault()
                                                                               select new
                    {
                        Width = l_graphic_extent != null?EmuUnit.EmuToPixels((int)l_graphic_extent.Attribute("cx")) : 0,
                                    Height = l_graphic_extent != null?EmuUnit.EmuToPixels((int)l_graphic_extent.Attribute("cy")) : 0,
                                                 ExternalRelationId = l_graphic_blip != null ? (string)l_graphic_blip.Attribute(rels + "embed") : ""
                    };

                    // Write graphics
                    foreach (var graphic in graphics)
                    {
                        // Write graphic
                        s +=
                            String.Format("<div style=\"float:left; clear:none; width:{1}px; height:{2}px; margin:5px;\"><img src=\"{0}\" width=\"{1}\" height=\"{2}\"/></div>",
                                          RenderInternalRelationshipLink(graphic.ExternalRelationId),
                                          graphic.Width,
                                          graphic.Height
                                          );
                    }

                    // Write text
                    s += RenderPlainText(run.Text);

                    // End hyperlink
                    if (run.RunType == "hyperlink")
                    {
                        s += "</a>";
                    }

                    // End run
                    s += "</span>";
                }

                s += "</p>\n\n";
            }
            return(s);
        }
        public void Apply(CharacterRun run, string startElement, RegularContainer slide, ref string lastColor, ref string lastSize, ref string lastTypeface, string lang, string altLang, TextMasterStyleAtom defaultStyle, int lvl, List <MouseClickInteractiveInfoContainer> mciics, ShapeTreeMapping parentShapeTreeMapping, uint position, bool insideTable)
        {
            _writer.WriteStartElement("a", startElement, OpenXmlNamespaces.DrawingML);


            if (lang.Length == 0)
            {
                TextSIExceptionAtom siea = _ctx.Ppt.DocumentRecord.FirstDescendantWithType <TextSIExceptionAtom>();
                if (siea != null)
                {
                    if (siea.si.lang)
                    {
                        switch (siea.si.lid)
                        {
                        case 0x0:     // no language
                            break;

                        case 0x13:     //Any Dutch language is preferred over non-Dutch languages when proofing the text
                            break;

                        case 0x400:     //no proofing
                            break;

                        default:
                            try
                            {
                                lang = System.Globalization.CultureInfo.GetCultureInfo(siea.si.lid).IetfLanguageTag;
                            }
                            catch (Exception)
                            {
                                //ignore
                            }
                            break;
                        }
                    }
                }
            }

            if (altLang.Length == 0)
            {
                TextSIExceptionAtom siea = _ctx.Ppt.DocumentRecord.FirstDescendantWithType <TextSIExceptionAtom>();
                if (siea != null)
                {
                    if (siea.si.altLang)
                    {
                        switch (siea.si.altLid)
                        {
                        case 0x0:     // no language
                            break;

                        case 0x13:     //Any Dutch language is preferred over non-Dutch languages when proofing the text
                            break;

                        case 0x400:     //no proofing
                            break;

                        default:
                            try
                            {
                                altLang = System.Globalization.CultureInfo.GetCultureInfo(siea.si.altLid).IetfLanguageTag;
                            }
                            catch (Exception)
                            {
                                //ignore
                            }
                            break;
                        }
                    }
                }
            }

            if (lang.Length > 0)
            {
                _writer.WriteAttributeString("lang", lang);
            }

            if (altLang.Length > 0)
            {
                _writer.WriteAttributeString("altLang", altLang);
            }

            bool runExists = run != null;

            if (runExists && run.SizePresent)
            {
                if (run.Size > 0)
                {
                    _writer.WriteAttributeString("sz", (run.Size * 100).ToString());
                    lastSize = (run.Size * 100).ToString();
                }
            }
            else if (lastSize.Length > 0)
            {
                _writer.WriteAttributeString("sz", lastSize);
            }
            else if (defaultStyle != null)
            {
                if (defaultStyle.CRuns[lvl].SizePresent)
                {
                    _writer.WriteAttributeString("sz", (defaultStyle.CRuns[lvl].Size * 100).ToString());
                }
            }

            if (runExists && run.StyleFlagsFieldPresent)
            {
                if ((run.Style & StyleMask.IsBold) == StyleMask.IsBold)
                {
                    _writer.WriteAttributeString("b", "1");
                }
                if ((run.Style & StyleMask.IsItalic) == StyleMask.IsItalic)
                {
                    _writer.WriteAttributeString("i", "1");
                }
                if ((run.Style & StyleMask.IsUnderlined) == StyleMask.IsUnderlined)
                {
                    _writer.WriteAttributeString("u", "sng");
                }
            }
            else if (defaultStyle != null && defaultStyle.CRuns[lvl].StyleFlagsFieldPresent)
            {
                if ((defaultStyle.CRuns[lvl].Style & StyleMask.IsBold) == StyleMask.IsBold)
                {
                    _writer.WriteAttributeString("b", "1");
                }
                if ((defaultStyle.CRuns[lvl].Style & StyleMask.IsItalic) == StyleMask.IsItalic)
                {
                    _writer.WriteAttributeString("i", "1");
                }
                if ((defaultStyle.CRuns[lvl].Style & StyleMask.IsUnderlined) == StyleMask.IsUnderlined)
                {
                    _writer.WriteAttributeString("u", "sng");
                }
            }

            if (runExists && run.ColorPresent)
            {
                writeSolidFill(slide, run, ref lastColor);
            }
            else if (lastColor.Length > 0)
            {
                _writer.WriteStartElement("a", "solidFill", OpenXmlNamespaces.DrawingML);
                _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                _writer.WriteAttributeString("val", lastColor);
                _writer.WriteEndElement();
                _writer.WriteEndElement();
            }
            else if (defaultStyle != null)
            {
                if (defaultStyle.CRuns[lvl].ColorPresent)
                {
                    writeSolidFill((RegularContainer)defaultStyle.ParentRecord, defaultStyle.CRuns[lvl], ref lastColor);
                }
            }

            if (runExists && run.StyleFlagsFieldPresent)
            {
                if ((run.Style & StyleMask.HasShadow) == StyleMask.HasShadow)
                {
                    //TODO: these values are default and have to be replaced
                    _writer.WriteStartElement("a", "effectLst", OpenXmlNamespaces.DrawingML);
                    _writer.WriteStartElement("a", "outerShdw", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("blurRad", "38100");
                    _writer.WriteAttributeString("dist", "38100");
                    _writer.WriteAttributeString("dir", "2700000");
                    _writer.WriteAttributeString("algn", "tl");
                    _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", "C0C0C0");
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();
                }

                if ((run.Style & StyleMask.IsEmbossed) == StyleMask.IsEmbossed)
                {
                    //TODO: these values are default and have to be replaced
                    _writer.WriteStartElement("a", "effectDag", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("name", "");
                    _writer.WriteStartElement("a", "cont", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("type", "tree");
                    _writer.WriteAttributeString("name", "");
                    _writer.WriteStartElement("a", "effect", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("ref", "fillLine");
                    _writer.WriteEndElement();
                    _writer.WriteStartElement("a", "outerShdw", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("dist", "38100");
                    _writer.WriteAttributeString("dir", "13500000");
                    _writer.WriteAttributeString("algn", "br");
                    _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", "FFFFFF");
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();
                    _writer.WriteStartElement("a", "cont", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("type", "tree");
                    _writer.WriteAttributeString("name", "");
                    _writer.WriteStartElement("a", "effect", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("ref", "fillLine");
                    _writer.WriteEndElement();
                    _writer.WriteStartElement("a", "outerShdw", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("dist", "38100");
                    _writer.WriteAttributeString("dir", "2700000");
                    _writer.WriteAttributeString("algn", "tl");
                    _writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("val", "999999");
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();
                    _writer.WriteStartElement("a", "effect", OpenXmlNamespaces.DrawingML);
                    _writer.WriteAttributeString("ref", "fillLine");
                    _writer.WriteEndElement();
                    _writer.WriteEndElement();
                }

                //TODOS
                //HasAsianSmartQuotes
                //HasHorizonNumRendering
                //ExtensionNibble
            }

            //TODOs:
            //run.ANSITypefacePresent
            //run.FEOldTypefacePresent
            //run.PositionPresent
            //run.SymbolTypefacePresent
            //run.TypefacePresent

            if (runExists && run.TypefacePresent)
            {
                _writer.WriteStartElement("a", "latin", OpenXmlNamespaces.DrawingML);
                try
                {
                    FontCollection fonts  = _ctx.Ppt.DocumentRecord.FirstChildWithType <DIaLOGIKa.b2xtranslator.PptFileFormat.Environment>().FirstChildWithType <FontCollection>();
                    FontEntityAtom entity = fonts.entities[(int)run.TypefaceIdx];
                    if (entity.TypeFace.IndexOf('\0') > 0)
                    {
                        _writer.WriteAttributeString("typeface", entity.TypeFace.Substring(0, entity.TypeFace.IndexOf('\0')));
                        lastTypeface = entity.TypeFace.Substring(0, entity.TypeFace.IndexOf('\0'));
                    }
                    else
                    {
                        _writer.WriteAttributeString("typeface", entity.TypeFace);
                        lastTypeface = entity.TypeFace;
                    }
                    //_writer.WriteAttributeString("charset", "0");
                }
                catch (Exception ex)
                {
                    throw;
                }

                _writer.WriteEndElement();
            }
            else if (lastTypeface.Length > 0)
            {
                _writer.WriteStartElement("a", "latin", OpenXmlNamespaces.DrawingML);
                _writer.WriteAttributeString("typeface", lastTypeface);
                _writer.WriteEndElement();
            }
            else if (defaultStyle != null && defaultStyle.CRuns[lvl].TypefacePresent)
            {
                _writer.WriteStartElement("a", "latin", OpenXmlNamespaces.DrawingML);
                try
                {
                    FontCollection fonts  = _ctx.Ppt.DocumentRecord.FirstChildWithType <DIaLOGIKa.b2xtranslator.PptFileFormat.Environment>().FirstChildWithType <FontCollection>();
                    FontEntityAtom entity = fonts.entities[(int)defaultStyle.CRuns[lvl].TypefaceIdx];
                    if (entity.TypeFace.IndexOf('\0') > 0)
                    {
                        _writer.WriteAttributeString("typeface", entity.TypeFace.Substring(0, entity.TypeFace.IndexOf('\0')));
                        lastTypeface = entity.TypeFace.Substring(0, entity.TypeFace.IndexOf('\0'));
                    }
                    else
                    {
                        _writer.WriteAttributeString("typeface", entity.TypeFace);
                        lastTypeface = entity.TypeFace;
                    }
                    //_writer.WriteAttributeString("charset", "0");
                }
                catch (Exception ex)
                {
                    throw;
                }

                _writer.WriteEndElement();
            }
            else
            {
                if (insideTable)
                {
                    if (slide.FirstChildWithType <SlideAtom>() != null && _ctx.Ppt.FindMasterRecordById(slide.FirstChildWithType <SlideAtom>().MasterId) != null)
                    {
                        foreach (TextMasterStyleAtom item in _ctx.Ppt.FindMasterRecordById(slide.FirstChildWithType <SlideAtom>().MasterId).AllChildrenWithType <TextMasterStyleAtom>())
                        {
                            if (item.Instance == 1)
                            {
                                if (item.CRuns.Count > 0 && item.CRuns[0].TypefacePresent)
                                {
                                    _writer.WriteStartElement("a", "latin", OpenXmlNamespaces.DrawingML);
                                    try
                                    {
                                        FontCollection fonts  = _ctx.Ppt.DocumentRecord.FirstChildWithType <DIaLOGIKa.b2xtranslator.PptFileFormat.Environment>().FirstChildWithType <FontCollection>();
                                        FontEntityAtom entity = fonts.entities[(int)item.CRuns[0].TypefaceIdx];
                                        if (entity.TypeFace.IndexOf('\0') > 0)
                                        {
                                            _writer.WriteAttributeString("typeface", entity.TypeFace.Substring(0, entity.TypeFace.IndexOf('\0')));
                                            lastTypeface = entity.TypeFace.Substring(0, entity.TypeFace.IndexOf('\0'));
                                        }
                                        else
                                        {
                                            _writer.WriteAttributeString("typeface", entity.TypeFace);
                                            lastTypeface = entity.TypeFace;
                                        }
                                        //_writer.WriteAttributeString("charset", "0");
                                    }
                                    catch (Exception ex)
                                    {
                                        throw;
                                    }

                                    _writer.WriteEndElement();
                                }
                            }
                        }
                    }
                }
                //        try
                //        {
                //            CharacterRun cr = _ctx.Ppt.DocumentRecord.FirstChildWithType<PptFileFormat.Environment>().FirstChildWithType<TextMasterStyleAtom>().CRuns[0];
                //            if (cr.TypefacePresent)
                //            {
                //                    FontCollection fonts = _ctx.Ppt.DocumentRecord.FirstChildWithType<DIaLOGIKa.b2xtranslator.PptFileFormat.Environment>().FirstChildWithType<FontCollection>();
                //                    FontEntityAtom entity = fonts.entities[(int)cr.TypefaceIdx];
                //                    if (entity.TypeFace.IndexOf('\0') > 0)
                //                    {
                //                        _writer.WriteStartElement("a", "latin", OpenXmlNamespaces.DrawingML);
                //                        _writer.WriteAttributeString("typeface", entity.TypeFace.Substring(0, entity.TypeFace.IndexOf('\0')));
                //                        _writer.WriteEndElement();
                //                    }
                //                    else
                //                    {
                //                        _writer.WriteStartElement("a", "latin", OpenXmlNamespaces.DrawingML);
                //                        _writer.WriteAttributeString("typeface", entity.TypeFace);
                //                        _writer.WriteEndElement();
                //                    }
                //                }
                //        }
                //        catch (Exception ex)
                //        {
                //            //throw;
                //        }
            }

            if (runExists && run.FEOldTypefacePresent)
            {
                try
                {
                    FontCollection fonts  = _ctx.Ppt.DocumentRecord.FirstChildWithType <DIaLOGIKa.b2xtranslator.PptFileFormat.Environment>().FirstChildWithType <FontCollection>();
                    FontEntityAtom entity = fonts.entities[(int)run.FEOldTypefaceIdx];
                    if (entity.TypeFace.IndexOf('\0') > 0)
                    {
                        _writer.WriteStartElement("a", "ea", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("typeface", entity.TypeFace.Substring(0, entity.TypeFace.IndexOf('\0')));
                        _writer.WriteEndElement();
                    }
                    else
                    {
                        _writer.WriteStartElement("a", "ea", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("typeface", entity.TypeFace);
                        _writer.WriteEndElement();
                    }
                }
                catch (Exception ex)
                {
                    //throw;
                }
            }
            else
            {
                try
                {
                    CharacterRun cr = _ctx.Ppt.DocumentRecord.FirstChildWithType <PptFileFormat.Environment>().FirstChildWithType <TextMasterStyleAtom>().CRuns[0];
                    if (cr.FEOldTypefacePresent)
                    {
                        FontCollection fonts  = _ctx.Ppt.DocumentRecord.FirstChildWithType <DIaLOGIKa.b2xtranslator.PptFileFormat.Environment>().FirstChildWithType <FontCollection>();
                        FontEntityAtom entity = fonts.entities[(int)cr.FEOldTypefaceIdx];
                        if (entity.TypeFace.IndexOf('\0') > 0)
                        {
                            _writer.WriteStartElement("a", "ea", OpenXmlNamespaces.DrawingML);
                            _writer.WriteAttributeString("typeface", entity.TypeFace.Substring(0, entity.TypeFace.IndexOf('\0')));
                            _writer.WriteEndElement();
                        }
                        else
                        {
                            _writer.WriteStartElement("a", "ea", OpenXmlNamespaces.DrawingML);
                            _writer.WriteAttributeString("typeface", entity.TypeFace);
                            _writer.WriteEndElement();
                        }
                    }
                }
                catch (Exception ex)
                {
                    //throw;
                }
            }

            if (runExists && run.SymbolTypefacePresent)
            {
                try
                {
                    FontCollection fonts  = _ctx.Ppt.DocumentRecord.FirstChildWithType <DIaLOGIKa.b2xtranslator.PptFileFormat.Environment>().FirstChildWithType <FontCollection>();
                    FontEntityAtom entity = fonts.entities[(int)run.SymbolTypefaceIdx];
                    if (entity.TypeFace.IndexOf('\0') > 0)
                    {
                        _writer.WriteStartElement("a", "sym", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("typeface", entity.TypeFace.Substring(0, entity.TypeFace.IndexOf('\0')));
                        _writer.WriteEndElement();
                    }
                    else
                    {
                        _writer.WriteStartElement("a", "sym", OpenXmlNamespaces.DrawingML);
                        _writer.WriteAttributeString("typeface", entity.TypeFace);
                        _writer.WriteEndElement();
                    }
                }
                catch (Exception ex)
                {
                    //throw;
                }
            }

            if (mciics != null && mciics.Count > 0)
            {
                foreach (MouseClickInteractiveInfoContainer mciic in mciics)
                {
                    InteractiveInfoAtom iia = mciic.FirstChildWithType <InteractiveInfoAtom>();
                    MouseClickTextInteractiveInfoAtom tiia = mciic.Range;

                    if (tiia.begin <= position && tiia.end > position)
                    {
                        if (iia != null)
                        {
                            if (iia.action == InteractiveInfoActionEnum.Hyperlink)
                            {
                                foreach (ExHyperlinkContainer c in _ctx.Ppt.DocumentRecord.FirstDescendantWithType <ExObjListContainer>().AllChildrenWithType <ExHyperlinkContainer>())
                                {
                                    ExHyperlinkAtom a = c.FirstChildWithType <ExHyperlinkAtom>();
                                    if (a.exHyperlinkId == iia.exHyperlinkIdRef)
                                    {
                                        CStringAtom          s  = c.FirstChildWithType <CStringAtom>();
                                        ExternalRelationship er = parentShapeTreeMapping.parentSlideMapping.targetPart.AddExternalRelationship(OpenXmlRelationshipTypes.HyperLink, s.Text);

                                        _writer.WriteStartElement("a", "hlinkClick", OpenXmlNamespaces.DrawingML);
                                        _writer.WriteAttributeString("r", "id", OpenXmlNamespaces.Relationships, er.Id.ToString());
                                        _writer.WriteEndElement();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            _writer.WriteEndElement();
        }