Пример #1
0
        /// <summary>
        /// Save CSS style into "".
        /// </summary>
        private static void AppendNewStyleAttribute(XmlDocument doc, CssStyle selector, XmlNode htmlNode)
        {
            CssStyleProperties style;

            if (htmlNode.Attributes == null)
            {
                return;
            }

            if (htmlNode.Attributes["new_style"] != null)
            {
                var oldStyleProperties = new CssStyleProperties {
                    Text = htmlNode.Attributes["new_style"].Value
                };
                var newStyleProperties = new CssStyleProperties {
                    Dictionary = selector.Properties.Dictionary
                };
                style = oldStyleProperties + newStyleProperties;
            }
            else
            {
                htmlNode.Attributes.Append(doc.CreateAttribute("new_style"));
                style = new CssStyleProperties {
                    Dictionary = selector.Properties.Dictionary
                };
            }

            htmlNode.Attributes["new_style"].Value = style.Text;
        }
Пример #2
0
        public CssStyle GetStyle(Style s, Style linkedStyle)
        {
            CssStyle cs = this.GetStyle(s);

            cs.CombineStyles(this.GetStyle(linkedStyle));
            return(cs);
        }
Пример #3
0
    /// <summary>
    /// 解析 CSS 样式属性
    /// </summary>
    /// <param name="styleExpression">CSS 样式设置表达式</param>
    /// <param name="specification">所需要采用的 CSS 规范</param>
    /// <returns>CSS 样式属性</returns>
    public static CssStyle ParseCssStyle( string styleExpression, CssStyleSpecificationBase specification = null )
    {

      var style = new CssStyle( specification ?? new Css21StyleSpecification() );
      style.SetProperties( ParseProperties( styleExpression ) );
      return style;
    }
Пример #4
0
 public void Remove(string key)
 {
     if (0 == String.Compare(key, StyleAttribute, true, Helpers.InvariantCulture))
     {
         CssStyle.Clear();
         return;
     }
     bag.Remove(key);
 }
Пример #5
0
        public CssStyle GetStyleFromRunProperties(RunProperties r, StyleConfig config = null)
        {
            CssStyle style = new CssStyle(null);
            var      rPr   = r;

            if (rPr != null)
            {
                if (rPr.RunFonts != null)
                {
                    if (config != null)
                    {
                        if (config.Charset == "Ascii")
                        {
                            if (rPr.RunFonts.Ascii != null || rPr.RunFonts.HighAnsi != null)
                            {
                                var fs = (rPr.RunFonts.Ascii != null ? rPr.RunFonts.Ascii.Value : "nofont")
                                         + "," + (rPr.RunFonts.HighAnsi != null ? rPr.RunFonts.HighAnsi.Value : "nofont");
                                style.AddStyle("font-family", fs);
                            }
                        }
                        if (config.Charset == "EastAsia")
                        {
                            if (rPr.RunFonts.EastAsia != null)
                            {
                                var fs = (rPr.RunFonts.EastAsia != null ? rPr.RunFonts.EastAsia.Value : "nofont");
                                style.AddStyle("font-family", fs);
                            }
                        }
                    }
                    else
                    {
                        var fs = (rPr.RunFonts.Ascii != null ? rPr.RunFonts.Ascii.Value : "nofont")
                                 + "," + (rPr.RunFonts.HighAnsi != null ? rPr.RunFonts.HighAnsi.Value : "nofont")
                                 + "," + (rPr.RunFonts.EastAsia != null ? rPr.RunFonts.EastAsia.Value : "nofont");
                        style.AddStyle("font-family", fs);
                    }
                }
                if (rPr.FontSize != null && rPr.FontSize.Val != null)
                {
                    style.AddStyle("font-size", rPr.FontSize.Val + "px");
                }
                if (rPr.Bold != null)
                {
                    if (rPr.Bold.Val != null && rPr.Bold.Val.Value)
                    {
                        style.AddStyle("font-weight", "bold");
                    }
                }
                if (rPr.Color != null)
                {
                    style.AddStyle("color", "#" + rPr.Color.Val);
                }
            }

            return(style);
        }
        public void When_rendering_CssStyle_Then_has_proper_attributes()
        {
            var control = new CssStyle("body { color: red; }");

            string actual  = control.ToString();
            var    element = this.GetHtmlNode(actual);

            Assert.That(element.Name, Is.EqualTo("style"));
            Assert.That(element.InnerText.Trim(), Is.EqualTo("body { color: red; }"));
            Assert.That(element.Attributes["type"].Value, Is.EqualTo("text/css"));
            Assert.That(element.Attributes["src"], Is.Null);
        }
        /// <summary>
        ///     Get simple Html string of a single class object with only new lines
        /// </summary>
        /// <param name="Class">Any entity object , can be null.</param>
        /// <param name="additionalStylesWithTable"></param>
        /// <param name="additionalStylesWithRow"></param>
        /// <param name="additionalStylesWithCell"></param>
        /// <returns>
        ///     Returns property and value string combination, returns empty string if class is null or doesn't have any valid
        ///     properties to display.
        /// </returns>
        public static string AsHtmlTable(object Class,
                                         string additionalStylesWithTable = "",
                                         string additionalStylesWithRow   = "",
                                         string additionalStylesWithCell  = "")
        {
            if (Class != null)
            {
                var properties =
                    Class.GetType()
                    .GetProperties(TypeOfPropertise)
                    .Where(p => p.Name != "EntityKey" && p.Name != "EntityState")
                    .ToList();
                var sb      = new StringBuilder(properties.Count * 3 + 20);
                var styles  = CssStyle.GetCommonStyles("#74DA74", "black", null, "8px 20px 16px", "4px");
                var styles2 = CssStyle.GetCommonStyles(null, null, null, null, null, "bolder");
                sb.Append("<table ");
                sb.Append("style='" + styles + additionalStylesWithTable + "'>");
                sb.Append("<thead>");
                //sb.Append(HtmlHelperExtension.GetTag("caption", "Entity Title : " + anyObject.ToString()));
                sb.Append("<tr ");
                sb.Append("style='" + styles2 + additionalStylesWithRow + "'>");
                sb.Append(HtmlHelperExtension.GetTag("td", "", additionalStylesWithCell));
                sb.Append(HtmlHelperExtension.GetTag("td", "", additionalStylesWithCell));
                sb.Append(HtmlHelperExtension.GetTag("td", "", additionalStylesWithCell));
                //sb.Append(HtmlHelperExtension.GetTag("td", "Properties"));
                //sb.Append(HtmlHelperExtension.GetTag("td", ""));
                //sb.Append(HtmlHelperExtension.GetTag("td", "Values"));
                sb.Append("</tr>");
                sb.Append("</thead>");
                sb.Append("<tbody>");

                foreach (var prop in properties)
                {
                    var val = prop.GetValue(Class, null);
                    sb.Append("<tr ");
                    sb.Append("style='" + additionalStylesWithRow + "'>");
                    if (TypeChecker.IsPrimitiveOrGuid(val))
                    {
                        sb.Append(HtmlHelperExtension.GetTag("td", prop.Name, additionalStylesWithCell));
                        sb.Append(":");
                        sb.Append(HtmlHelperExtension.GetTag("td", val.ToString(), additionalStylesWithCell));
                    }
                    sb.Append("</tr>");
                }
                sb.Append("</tbody>");
                sb.Append("</table>");
                var output = sb.ToString();
                sb = null;
                GC.Collect();
                return(output);
            }
            return("");
        }
Пример #8
0
        /// <summary>
        /// 确保当前跟踪的样式是最新的
        /// </summary>
        private void EnsureStyle()
        {
            lock (_element.SyncRoot)
            {
                var styleAttribute = _element.Attribute("style");

                if (_style == null || styleAttribute != _attribute || (styleAttribute == null && _style.Any()))
                {
                    _style     = CssPropertyParser.ParseCssStyle(styleAttribute.Value().IfNull(""));
                    _attribute = styleAttribute;
                }
            }
        }
Пример #9
0
        public CssStyle GetStyle(Style s, StyleConfig config = null)
        {
            CssStyle cs = new CssStyle();

            if (s == null)
            {
                return(cs);
            }
            var id   = s.StyleId;
            var type = s.Type.ToString();

            if (type == "paragraph")
            {
                if (s.StyleParagraphProperties != null)
                {
                    CssStyle cS = this.GetStyleFromParagraphProperties(new ParagraphProperties(s.StyleParagraphProperties.OuterXml), config);
                    cS.Selector = ".Inner_P_" + id;
                    if (s.StyleRunProperties != null)
                    {
                        CssStyle cSs = this.GetStyleFromRunProperties(new RunProperties(s.StyleRunProperties.OuterXml), config);
                        cS.CombineStyles(cSs);
                    }
                    return(cS);
                }
            }
            else if (type == "character")
            {
                if (s.StyleRunProperties != null)
                {
                    CssStyle cS = this.GetStyleFromRunProperties(new RunProperties(s.StyleRunProperties.OuterXml), config);
                    cS.Selector = ".Inner_R_" + id;
                    return(cS);
                }
            }
            else if (type == "table")
            {
                if (s.StyleTableProperties != null)
                {
                    CssStyle cS = this.GetStyleFromTableProperties(new TableProperties(s.StyleTableProperties.OuterXml), config);
                    cS.Selector = ".Inner_T_" + id;
                    return(cS);
                }
            }
            else if (type == "numbering")
            {
            }
            else if (type == "direct")
            {
            }
            return(cs);
        }
Пример #10
0
        private void CSSEdit(string path, bool fontEmbed)
        {
            FileStream   fst = new FileStream(path, FileMode.Open);
            StreamReader sr  = new StreamReader(fst);

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

            Logger.logger.Info($"Read .css from stream");
            while (sr.EndOfStream != true)
            {
                _cssstrings.Add(sr.ReadLine());
            }
            fst.Close();
            Logger.logger.Debug($"Create file :{path}");
            FileStream   rst    = new FileStream(path, FileMode.Create);
            StreamWriter sw     = new StreamWriter(rst);
            Regex        reBody = new Regex(@"[bB][oO][dD][yY][\s]*[{]");
            Regex        reHtml = new Regex(@"[Hh][Tt][Mm][Ll][\s]*[{]");

            Logger.logger.Info($"Define CssStyle ");
            Logger.logger.Info($"Replace \"body\" ");
            CssStyle css = new CssStyle(_cssstrings, reBody, "body");

            // _cssstrings = css.Replace();
            css.Replace();
            Logger.logger.Debug($"Replace \"html\" ");
            css.NewReplacement(reHtml, "html");
            css.Replace();
            _cssstrings = css.GetCss();

            //以下待修整



            sw.AutoFlush = true;
            foreach (string item in _cssstrings)
            {
                sw.WriteLine(item);
            }



            //if (htmlStart == -1 | CssSource.IndexOf("html{") == -1)//判定是否皆為true, | <--OR
            //{



            rst.Flush();
            rst.Close();
        }
Пример #11
0
        protected override void Render(HtmlTextWriter writer)
        {
            List <Control> iconAndTextControls = new List <Control>();

            if (this.Icon != null && this.IconPosition == Position.Left)
            {
                iconAndTextControls.Add(Icon);
            }

            iconAndTextControls.Add(new LiteralControl(this.Text));

            if (this.Icon != null && this.IconPosition == Position.Right)
            {
                iconAndTextControls.Add(Icon);
            }

            string onClick = "";

            if (Page != null)
            {
                if (CausesValidation || ValidationGroup.IsSet())
                {
                    PostBackOptions options = new PostBackOptions(this);
                    options.ValidationGroup   = this.ValidationGroup;
                    options.PerformValidation = true;
                    onClick = Page.ClientScript.GetPostBackEventReference(options, true);
                }
                else
                {
                    onClick = Page.ClientScript.GetPostBackClientHyperlink(this, "");
                }
            }

            writer.WriteHtmlElement(new HtmlElement(
                                        type: Type,
                                        attributes: new HtmlAttribute[] {
                new HtmlClassAttribute(CssClass, Size.ToRender(), CssStyle.ToRender()),
                new HtmlTypeAttribute("submit"),
                new HtmlNameAttribute(this.UniqueID),
                new HtmlAttribute("disabled", "disabled", !IsEnabled),
                new HtmlAttribute("data-toggle", "button", IsToggleable),
                new HtmlAttribute("onclick", onClick, !UseSubmitBehavior)
            },
                                        controls: iconAndTextControls.ToArray()
                                        ));
        }
Пример #12
0
        /// <summary>
        /// 为已经添加到OB中的Style增加新的样式
        /// 注意:这个key-value不会保存到属性CssStyle中
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        protected void AddExtraStyle(string key, string value)
        {
            // string style = OB.GetProperty(OptionName.Style);
            // 这样不行,添加到OB中的字符串都是被编码过的
            // 比如"margin-right:5px;"被添加到OB中就变成:"\"margin-right:5px;\"",在JsObjectBuilder中的AddProperty中处理的。
            // 这样做是为了在JsObjectBuilder中的ToString中,这样来添加属性:sb.AppendFormat("{0}:{1},", key, _properties[key]);


            string style = CssStyle.ToLower();

            if (style == "" || !style.Contains(key))
            {
                style += String.Format("{0}:{1};", key, value);
            }

            OB.AddProperty("style", style);
        }
Пример #13
0
        public CssStyle GetStyleFromParagraphProperties(ParagraphProperties p, StyleConfig config = null)
        {
            CssStyle style = new CssStyle(null);
            var      pPr   = p;

            if (pPr != null)
            {
                if (pPr.Justification != null)
                {
                    var jc = pPr.Justification;
                    style.AddStyle("text-align", jc.Val);
                }
                if (pPr.ParagraphMarkRunProperties != null)
                {
                    RunProperties rPr = new RunProperties(pPr.ParagraphMarkRunProperties.OuterXml);
                    CssStyle      p_s = this.GetStyleFromRunProperties(rPr, config);
                    style.CombineStyles(p_s);
                }
            }
            return(style);
        }
Пример #14
0
        protected override void Render(HtmlTextWriter writer)
        {
            HtmlClassAttribute titleClass =
                HasSeparatedArrow ?
                new HtmlClassAttribute("btn", CssStyle.ToRender(), Size.ToRender()):
                new HtmlClassAttribute("btn", CssStyle.ToRender(), Size.ToRender(), "dropdown-toggle");

            writer.WriteHtmlElement(new HtmlElement(
                                        attributes: new HtmlAttribute[] {
                new HtmlClassAttribute("btn-group", Direction.ToRender())
            },
                                        elements: new HtmlElement[] {
                new HtmlElement(
                    type: HtmlTextWriterTag.Button,
                    attributes: new HtmlAttribute[] {
                    new HtmlTypeAttribute("button"),
                    titleClass,
                    new HtmlAttribute("data-toggle", "dropdown", !HasSeparatedArrow)
                },
                    content: this.Text,
                    elements: new HtmlElement[] {
                    new HtmlCaretElement(!HasSeparatedArrow)
                }
                    ),
                new HtmlElement(
                    isRendered: HasSeparatedArrow,
                    type: HtmlTextWriterTag.Button,
                    attributes: new HtmlAttribute[] {
                    new HtmlTypeAttribute("button"),
                    new HtmlClassAttribute("btn", CssStyle.ToRender(), "dropdown-toggle"),
                    new HtmlAttribute("data-toggle", "dropdown")
                },
                    content: CARET
                    )
            },
                                        controls: new Control[] {
                Menu
            }
                                        ));
        }
Пример #15
0
        protected override void Render(HtmlTextWriter writer)
        {
            this.EnsureChildControls();

            Control[] headerCtrls = new Control[this.HeaderControls.Controls.Count];
            this.HeaderControls.Controls.CopyTo(headerCtrls, 0);

            Control[] bodyCtrls = new Control[this.BodyControls.Controls.Count];
            this.BodyControls.Controls.CopyTo(bodyCtrls, 0);

            Control[] footerCtrls = new Control[this.FooterControls.Controls.Count];
            this.FooterControls.Controls.CopyTo(footerCtrls, 0);

            writer.WriteHtmlElement(new HtmlElement(
                                        attributes: new HtmlAttribute[] {
                new HtmlClassAttribute("panel", CssStyle.ToRender(), CssClass)
            },
                                        elements: new HtmlElement[] {
                new HtmlElement(
                    attributes: new HtmlAttribute[] {
                    new HtmlClassAttribute("panel-heading")
                },
                    controls: headerCtrls
                    ),
                new HtmlElement(
                    attributes: new HtmlAttribute[] {
                    new HtmlClassAttribute("panel-body")
                },
                    controls: bodyCtrls
                    ),
                new HtmlElement(
                    isRendered: this.ShowFooter,
                    attributes: new HtmlAttribute[] {
                    new HtmlClassAttribute("panel-footer")
                },
                    controls: footerCtrls
                    ),
            }
                                        ));
        }
Пример #16
0
        /// <summary>
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="method"></param>
        /// <param name="entitySingleObject"></param>
        public void GenerateErrorBody(Exception ex, ref string subject, ref string body, string method = "",
                                      object entitySingleObject = null)
        {
            var isUserExist = HttpContext.Current != null && HttpContext.Current.User.Identity.IsAuthenticated;

            var sb = new StringBuilder(30);

            if (body == null)
            {
                body = "";
            }

            sb.Append(GetErrorMsgHtml(ex, method));

            if (string.IsNullOrEmpty(subject))
            {
                subject = string.Format("[{0}] [Error] on [{1}] method at {2}", Config.ApplicationName, method,
                                        DateTime.UtcNow);
            }
            if (isUserExist)
            {
                sb.Append("<hr />");
                var loggedUserStyle = CssStyle.GetCommonStyles("Green", "White", "0 0 5px 0", "8px", "3px", "bolder");
                sb.Append(HtmlHelperExtension.GetTag("div", "Logged in user : "******"<hr/>");
                sb.Append(HtmlHelperExtension.GetTag("h3", "Entity Title : " + entitySingleObject));
                try {
                    var entityString = EntityToString.GetHtmlOfSingleClassAsTable(entitySingleObject);
                    sb.Append(entityString);
                } catch (Exception ex2) {
                    sb.Append("<div style='color:red'> Error Can't Read Entity: " + ex2.Message + "</div>");
                }
            }
            sb.Append("<hr />");
            sb.Append("<div style='background-color:#FFFFD1" + Config.CommonStyles + "> Stack Trace: " + ex.StackTrace + "</div>");
            body = sb.ToString();
        }
Пример #17
0
        protected override void Render(HtmlTextWriter writer)
        {
            this.EnsureChildControls();

            Control[] leftCtrls = new Control[this.LeftControls.Controls.Count];
            this.LeftControls.Controls.CopyTo(leftCtrls, 0);

            Control[] rightCtrls = new Control[this.RightControls.Controls.Count];
            this.RightControls.Controls.CopyTo(rightCtrls, 0);

            writer.WriteHtmlElement(new HtmlElement(
                                        name: "nav",
                                        attributes: new HtmlAttribute[] {
                new HtmlClassAttribute("navbar", CssStyle.ToRender(), Position.ToRender()),
                new HtmlAttribute("role", "navigation")
            },
                                        elements: new HtmlElement[] {
                new HtmlElement(
                    attributes: new HtmlAttribute[] {
                    new HtmlClassAttribute("navbar-header")
                },
                    elements: new HtmlElement[] {
                    new HtmlElement(
                        type: HtmlTextWriterTag.A,
                        attributes: new HtmlAttribute[] {
                        new HtmlClassAttribute("navbar-brand"),
                        new HtmlHrefAttribute(this.BrandNavigateUrl),
                    },
                        content: this.BrandText
                        )
                }
                    ),
                new HtmlElement(
                    attributes: new HtmlAttribute[] {
                    new HtmlClassAttribute("collapse", "navbar-collapse", "navbar-ex1-collapse")
                },
                    elements: new HtmlElement[] {
                    new HtmlElement(
                        type: HtmlTextWriterTag.Ul,
                        attributes: new HtmlAttribute[] {
                        new HtmlClassAttribute("nav", "navbar-nav")
                    },
                        controls: leftCtrls
                        ),
                    new HtmlElement(
                        isRendered: this.ShowSearch,
                        attributes: new HtmlAttribute[] {
                        new HtmlClassAttribute("navbar-form", this.SearchBarPosition == Bootstrap.NET.Position.Left ? "navbar-left" : "navbar-right"),
                        new HtmlAttribute("role", "search")
                    },
                        controls: new Control[] {
                        searchInput,
                        searchButton
                    }
                        ),
                    new HtmlElement(
                        type: HtmlTextWriterTag.Ul,
                        attributes: new HtmlAttribute[] {
                        new HtmlClassAttribute("nav", "navbar-nav", "navbar-right")
                    },
                        controls: rightCtrls
                        )
                }
                    )
            }
                                        ));
        }
Пример #18
0
 public void Clear()
 {
     CssStyle.Clear();
     bag.Clear();
 }
Пример #19
0
        static HtmlStyles()
        {
            XmlDocument xDoc       = new XmlDocument();
            Stream      dataStream = Support.GetResourceStream("CsQuery.Resources." + CssDefs);

            xDoc.Load(dataStream);

            XmlNamespaceManager nsMan = new XmlNamespaceManager(xDoc.NameTable);

            nsMan.AddNamespace("cssmd", "http://schemas.microsoft.com/Visual-Studio-Intellisense/css");

            var nodes = xDoc.DocumentElement.SelectNodes("cssmd:property-set/cssmd:property-def", nsMan);

            string type;

            foreach (XmlNode el in nodes)
            {
                CssStyle st = new CssStyle();
                st.Name = el.Attributes["_locID"].Value;
                type    = el.Attributes["type"].Value;
                switch (type)
                {
                case "length": st.Type = CssStyleType.Unit; break;

                case "color": st.Type = CssStyleType.Color; break;

                case "composite": st.Type = CssStyleType.Composite;
                    st.Format             = el.Attributes["syntax"].Value;
                    break;

                case "enum":
                case "enum-length":

                    if (type == "enum-length")
                    {
                        st.Type = CssStyleType.UnitOption;
                    }
                    else
                    {
                        st.Type = CssStyleType.Option;
                    }
                    st.Options = new HashSet <string>(el.Attributes["enum"].Value
                                                      .Split(StringSep, StringSplitOptions.RemoveEmptyEntries));
                    break;

                case "font":
                    st.Type = CssStyleType.Font;
                    break;

                case "string":
                    st.Type = CssStyleType.String;
                    break;

                case "url":
                    st.Type = CssStyleType.Url;
                    break;

                default:
                    throw new NotImplementedException("Error parsing css xml: unknown type '" + type + "'");
                }
                st.Description     = el.Attributes["description"].Value;
                StyleDefs[st.Name] = st;
            }
        }
Пример #20
0
    /// <summary>
    /// 确保当前跟踪的样式是最新的
    /// </summary>
    private void EnsureStyle()
    {
      lock ( _element.SyncRoot )
      {
        var styleAttribute = _element.Attribute( "style" );

        if ( _style == null || styleAttribute != _attribute || (styleAttribute == null && _style.Any()) )
        {
          _style = CssPropertyParser.ParseCssStyle( styleAttribute.Value().IfNull( "" ) );
          _attribute = styleAttribute;
        }
      }
    }
Пример #21
0
 void Ctrl_PreRender(object sender, EventArgs e)
 {
     Ctrl.Attributes.Add("style", CssStyle.ToString());
 }
Пример #22
0
 public CssStyleProperty TryGetShorthandProperty( CssStyle cssStyle )
 {
   return null;
 }
Пример #23
0
		/// <summary>
		/// Save CSS style into "".
		/// </summary>
		private static void AppendNewStyleAttribute(XmlDocument doc, CssStyle selector, XmlNode htmlNode)
		{
			CssStyleProperties style;

			if (htmlNode.Attributes == null)
				return;

			if (htmlNode.Attributes["new_style"] != null)
			{
				var oldStyleProperties = new CssStyleProperties { Text = htmlNode.Attributes["new_style"].Value };
				var newStyleProperties = new CssStyleProperties { Dictionary = selector.Properties.Dictionary };
				style = oldStyleProperties + newStyleProperties;
			}
			else
			{
				htmlNode.Attributes.Append(doc.CreateAttribute("new_style"));
				style = new CssStyleProperties { Dictionary = selector.Properties.Dictionary };
			}

			htmlNode.Attributes["new_style"].Value = style.Text;
		}
Пример #24
0
 private void ApplyCellBorderFromStyle(IWorksheetCellFormat cellFormat, CssStyle cssStyle)
 {
     if (this.IsValidBorder(cssStyle.Border.Left) && cellFormat.LeftBorderColor.IsEmpty)
         cellFormat.LeftBorderColor = cssStyle.Border.Left.Color;
     if (this.IsValidBorder(cssStyle.Border.Right) && cellFormat.RightBorderColor.IsEmpty)
         cellFormat.RightBorderColor = cssStyle.Border.Right.Color;
     if (this.IsValidBorder(cssStyle.Border.Top) && cellFormat.TopBorderColor.IsEmpty)
         cellFormat.TopBorderColor = cssStyle.Border.Top.Color;
     if (this.IsValidBorder(cssStyle.Border.Bottom) && cellFormat.BottomBorderColor.IsEmpty)
         cellFormat.BottomBorderColor = cssStyle.Border.Bottom.Color;
     cellFormat.LeftBorderStyle = this.ConvertWebToExcelBorderStyle(cellFormat.LeftBorderStyle, cssStyle.Border.Left.Style, cssStyle.Border.Left.Width);
     cellFormat.TopBorderStyle = this.ConvertWebToExcelBorderStyle(cellFormat.TopBorderStyle, cssStyle.Border.Top.Style, cssStyle.Border.Top.Width);
     cellFormat.RightBorderStyle = this.ConvertWebToExcelBorderStyle(cellFormat.RightBorderStyle, cssStyle.Border.Right.Style, cssStyle.Border.Right.Width);
     cellFormat.BottomBorderStyle = this.ConvertWebToExcelBorderStyle(cellFormat.BottomBorderStyle, cssStyle.Border.Bottom.Style, cssStyle.Border.Bottom.Width);
 }
Пример #25
0
        static void Main(string[] args)
        {
            string file = "./data/word.docx";

            file = "./data/DirectX_9_3D.docx";

            const string ROOT = "./OUT/";

            string fileMd5 = Utities.GetMd5(Path.GetFileName(file));
            string docRoot = Path.Combine(new[] { ROOT, fileMd5 + "/" });

            ConvertConfig config = new ConvertConfig
            {
                ResourcePath = "./" + fileMd5 + "/"
            };

            if (!Directory.Exists(docRoot))
            {
                Console.WriteLine("Unzip File");
                UnZip un = new UnZip();
                un.UnZipToDir(file, docRoot);
            }

            Console.WriteLine("Convert Word to Html");

            OpenXmlHelper helper = new OpenXmlHelper();

            Html.Html html = new Html.Html();

            HtmlElement meta0 = new HtmlElement("meta", false);

            meta0.AddAttribute("http-equiv", "X-UA-Compatible");
            meta0.AddAttribute("content", "IE=edge,chrome=1");

            HtmlElement meta1 = new HtmlElement("meta", false);

            meta1.AddAttribute("name", "viewport");
            meta1.AddAttribute("content", "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no");

            HtmlElement meta2 = new HtmlElement("meta", false);

            meta2.AddAttribute("name", "apple-mobile-web-app-capable");
            meta2.AddAttribute("content", "yes");

            HtmlElement meta3 = new HtmlElement("meta", false);

            meta3.AddAttribute("http-equiv", "content-type");
            meta3.AddAttribute("content", "text/html; charset=UTF-8");

            html.AddHeadElement(meta0);
            html.AddHeadElement(meta1);
            html.AddHeadElement(meta2);
            html.AddHeadElement(meta3);

            CSS      css  = new CSS();
            CssStyle body = new CssStyle("body");

            body.AddStyle("background-color", "gray");
            CssStyle center = new CssStyle(".center");

            center.AddStyle("text-align", "center");
            css.AddStyle(body);
            //css.AddStyle(center);
            html.AddStyle(css);

            HtmlElement   div      = new HtmlElement("div");
            HtmlAttribute divClass = new HtmlAttribute("class", "documentbody");

            div.AddAttribute(divClass);
            CssStyle divStyle = new CssStyle();

            divStyle.AddStyle("font-family", "'Times New Roman' 宋体");
            divStyle.AddStyle("font-size", "10.5pt");
            divStyle.AddStyle("margin", "0 auto");
            divStyle.AddStyle("width", "600px");
            divStyle.AddStyle("padding", "100px 120px");
            divStyle.AddStyle("border", "2px solid gray");
            divStyle.AddStyle("background-color", "white");

            div.AddStyle(divStyle);

            #region docuemnt

            WordprocessingDocument doc = WordprocessingDocument.Open(file, false);

            //StyleParts
            StylesPart docstyles = doc.MainDocumentPart.StyleDefinitionsPart == null
                ? doc.MainDocumentPart.StylesWithEffectsPart
                : (StylesPart)doc.MainDocumentPart.StyleDefinitionsPart;
            var styles = docstyles.Styles;
            //styles
            var styleEl = styles.Elements <Style>();
            //var i = __styles.Count();
            //生产Style模版对应的CSS Style
            html.AddStyle(helper.GetStyles(styleEl));

            var pps = doc.MainDocumentPart.Document.Body.ChildElements;

            ElementHandler handler = new ElementHandler(doc);

            //处理各个Word元素
            foreach (var pp in pps)
            {
                //Console.WriteLine(pp.GetType().ToString());
                div.AddChild(handler.Handle(pp, config));
            }

            #endregion
            html.AddElement(div);

            string     htmlfile = ROOT + fileMd5 + ".html";
            FileStream fs       = File.Exists(htmlfile)
                ? new FileStream(htmlfile, FileMode.Truncate, FileAccess.Write)
                : new FileStream(htmlfile, FileMode.CreateNew, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(html.ToString());
            sw.Close();
            fs.Close();

            ////
            //XDocument _styles = null;

            //if (docstyles != null)
            //{
            //    using (var reader = XmlReader.Create(docstyles.GetStream(FileMode.Open, FileAccess.Read)))
            //    {
            //        _styles = XDocument.Load(reader);
            //    }

            //}
            //if (_styles != null)
            //{
            //    //Console.WriteLine(_styles.ToString());
            //}
        }
Пример #26
0
 private IWorksheetCellFormat ApplyCellFormatFromStyle(Workbook workbook, IWorksheetCellFormat cellFormat, CssStyle cssStyle, WebDataGrid grid)
 {
     if (Color.Empty != cssStyle.Background.Color && cssStyle.Background.Color.ToArgb() != Color.White.ToArgb())
     {
         cellFormat.FillPatternForegroundColor = cssStyle.Background.Color;
         cellFormat.FillPattern = FillPatternStyle.Solid;
     }
     IWorkbookFont newWorkbookFont = workbook.CreateNewWorkbookFont();
     newWorkbookFont.Color = grid.ForeColor.IsEmpty ? cssStyle.Color : grid.ForeColor;
     newWorkbookFont.Name = string.IsNullOrEmpty(grid.Font.Name) ? cssStyle.Font.FamilyName : grid.Font.Name;
     switch (cssStyle.Font.SizeEnum)
     {
         case Infragistics.Documents.Reports.FontSize.NotSet:
             newWorkbookFont.Height = cssStyle.Font.SizeUnit.Type != UnitType.Point || cssStyle.Font.SizeUnit.Value < 1.0 ? (cssStyle.Font.SizeUnit.Type != UnitType.Pixel || cssStyle.Font.SizeUnit.Value < 1.0 ? 240 : (int)(cssStyle.Font.SizeUnit.Value * 20.0)) : (int)(cssStyle.Font.SizeUnit.Value * 20.0);
             break;
         case Infragistics.Documents.Reports.FontSize.Large:
         case Infragistics.Documents.Reports.FontSize.Larger:
             newWorkbookFont.Height = 280;
             break;
         case Infragistics.Documents.Reports.FontSize.Small:
         case Infragistics.Documents.Reports.FontSize.Smaller:
             newWorkbookFont.Height = 200;
             break;
         case Infragistics.Documents.Reports.FontSize.X_Large:
             newWorkbookFont.Height = 360;
             break;
         case Infragistics.Documents.Reports.FontSize.X_Small:
             newWorkbookFont.Height = 180;
             break;
         case Infragistics.Documents.Reports.FontSize.XX_Large:
             newWorkbookFont.Height = 480;
             break;
         case Infragistics.Documents.Reports.FontSize.XX_Small:
             newWorkbookFont.Height = 160;
             break;
         default:
             newWorkbookFont.Height = 240;
             break;
     }
     if (cssStyle.Font.IsBold || cssStyle.Font.Style == Infragistics.Documents.Reports.FontStyle.Oblique || grid.Font.Bold)
         newWorkbookFont.Bold = ExcelDefaultableBoolean.True;
     if (cssStyle.Font.IsItalic || cssStyle.Font.Style == Infragistics.Documents.Reports.FontStyle.Italic || grid.Font.Italic)
         newWorkbookFont.Italic = ExcelDefaultableBoolean.True;
     if (cssStyle.TextDecoration == TextDecoration.Line_Through || grid.Font.Strikeout)
         newWorkbookFont.Strikeout = ExcelDefaultableBoolean.True;
     if (cssStyle.TextDecoration == TextDecoration.Underline || grid.Font.Underline)
         newWorkbookFont.UnderlineStyle = FontUnderlineStyle.Single;
     cellFormat.Font.SetFontFormatting(newWorkbookFont);
     switch (cssStyle.TextAlign)
     {
         case Infragistics.Documents.Reports.TextAlign.Center:
             cellFormat.Alignment = HorizontalCellAlignment.Center;
             break;
         case Infragistics.Documents.Reports.TextAlign.Justify:
             cellFormat.Alignment = HorizontalCellAlignment.Justify;
             break;
         case Infragistics.Documents.Reports.TextAlign.Left:
             cellFormat.Alignment = HorizontalCellAlignment.Left;
             break;
         case Infragistics.Documents.Reports.TextAlign.Right:
             cellFormat.Alignment = HorizontalCellAlignment.Right;
             break;
         default:
             cellFormat.Alignment = HorizontalCellAlignment.General;
             break;
     }
     switch (cssStyle.VerticalAlign)
     {
         case Infragistics.Documents.Reports.VerticalAlign.Bottom:
             cellFormat.VerticalAlignment = VerticalCellAlignment.Bottom;
             break;
         case Infragistics.Documents.Reports.VerticalAlign.Middle:
             cellFormat.VerticalAlignment = VerticalCellAlignment.Center;
             break;
         case Infragistics.Documents.Reports.VerticalAlign.Top:
             cellFormat.VerticalAlignment = VerticalCellAlignment.Top;
             break;
         default:
             cellFormat.VerticalAlignment = VerticalCellAlignment.Default;
             break;
     }
     return cellFormat;
 }
Пример #27
0
        public CssStyle GetStyleFromTableProperties(TableProperties r, StyleConfig config = null)
        {
            CssStyle _style = new CssStyle(null);

            return(_style);
        }