SetAttributeValue() public méthode

Helper method to set the value of an attribute of this node. If the attribute is not found, it will be created automatically.
public SetAttributeValue ( string name, string value ) : HtmlAgilityPack.HtmlAttribute
name string The name of the attribute to set. May not be null.
value string The value for the attribute.
Résultat HtmlAgilityPack.HtmlAttribute
        public bool SetValue(HtmlNode n, string value)
        {
            if (n is HtmlNode && n.Name == "select")
            {
                foreach (HtmlNode o in n.SelectNodes("option"))
                {
                    o.SetAttributeValue("selected", o.GetAttributeValue("value", "").Equals(value) ? "selected" : "");
                }
                return true;
            }

            if (n is HtmlNode && n.Name == "input")
            {
                switch (n.GetAttributeValue("type", ""))
                {
                    case "radio":
                        n.SetAttributeValue("checked", n.GetAttributeValue("value", "").Equals(value) ? "checked" : "");
                        break;
                    default:
                        n.SetAttributeValue("value", value);
                        break;
                }
                n.SetAttributeValue("value", value);
                return true;
            }

            return false;
        }
        private static ExternalReference GetExternalReference(HtmlNode externalReferenceNode, int index)
        {
            string referenceUrl = externalReferenceNode.GetAttributeValue("href", string.Empty);
            string referenceId = GetExternalReferenceId(index);

            externalReferenceNode.InnerHtml = string.Format("[{0}]", index);
            externalReferenceNode.SetAttributeValue("href", "#" + referenceId);
            externalReferenceNode.SetAttributeValue("name", referenceId + BackLinkReferenceIdSuffix);

            return new ExternalReference { Index = index, Url = referenceUrl };
        }
Exemple #3
0
 /// <summary>
 /// 递归遍历内容中的图片
 /// </summary>
 /// <param name="node"></param>
 /// <returns></returns>
 public static void EachImages(HtmlNode node, string baseUri = "")
 {
     //判断是否有子标签
     if (node.HasChildNodes)
         foreach (HtmlNode nn in node.ChildNodes)
             EachImages(nn, baseUri);
     else if (node.Name == "img")
     {
         //图片
         string url = node.GetAttributeValue("src", "");
         if (url == "") return;
         //获取图片信息,生成新的路径
         //getimages/{Year}/{Week}/{FileName}
         string exe = Path.GetExtension(url).TrimStart(new char[] { '.' });
         string fileName = Guid.NewGuid().ToString() + "." + exe;
         int day = DateTime.Now.Day;
         //相对路径
         string fullName = string.Format("autoimages\\{0}\\{3}\\{1}\\{2}." + exe, DateTime.Now.Year, day <= 10 ? 1 : (day <= 20 ? 2 : 3), Guid.NewGuid().ToString(), DateTime.Now.Month);
         //网站
         string urlNew = "/" + fullName.Replace("\\", "/");
         node.SetAttributeValue("src", urlNew);
         //保存到本地
         Uri uri = baseUri == "" ? new Uri(url) : new Uri(new Uri(baseUri), url);
         SaveImg(uri.AbsoluteUri, fullName);
     }
 }
        public static void AddClass(this HtmlNode node, String cls)
        {
            var clses = node.GetAttributeValue("class", "");

            if (clses != "")
            {
                clses += " ";
            }
            clses += cls;
            node.SetAttributeValue("class", clses);
        }
Exemple #5
0
        /// <summary>
        /// Updates the inline styles for a given HTML node
        /// </summary>
        /// <param name="element">The HTML node to update inline styles for</param>
        /// <param name="declaration">The CSS declaration containing the styles to update the HTML node with</param>
        public static void UpdateInlineStyleForElement(HtmlNode element, Declaration declaration)
        {
            var style = element.GetAttributeValue("style", String.Empty);

            if (!HasDeclarationDefinedInline(declaration, style))
            {
                style += String.Format("{0}{1};", style == String.Empty ? String.Empty : " ", declaration);
            }
            else
            {
                var regex = new Regex(string.Format(@"(?<={0}:\s)(.*?)(?=;)", declaration.Name));
                style = regex.Replace(style, declaration.Expression.ToString());
            }

            element.SetAttributeValue("style", style);
        }
Exemple #6
0
        static string BuildAttributeString(HtmlNode node)
        {
            string name = node.Name.ToLower();

            if (name == "a") {
                node.SetAttributeValue("href", SanitizeAHref(node.GetAttributeValue("href", String.Empty)));

                // Don't allow custom titles (tooltips), and make sure one is always set.
                node.SetAttributeValue("title", node.GetAttributeValue("href", String.Empty));

                Console.WriteLine("SET ATTRIBUTE VALUE !! " + node.GetAttributeValue("title", "frak"));
            }

            if (name == "img") {
                node.SetAttributeValue("src", SanitizeImgSrc(node.GetAttributeValue("src", String.Empty)));

                // FIXME:

                // Show something if the image fails to load for some reason.
                //node.SetAttributeValue("alt", "[IMAGE]");

                // Force width
                //node.SetAttributeValue("width", "100%");

                // Remove height
                //node.SetAttributeValue("height", String.Empty);
            }

            var attributeStringBuilder = new StringBuilder();
            foreach (var attr in node.Attributes) {
                string attrName = attr.Name.ToLower();
                string attrVal = attr.Value;
                Console.WriteLine(attrName);
                if (s_WhiteList[name] != null && s_WhiteList[name].Contains(attrName)) {
                    if (attributeStringBuilder.Length > 0)
                        attributeStringBuilder.Append(" ");
                    attributeStringBuilder.AppendFormat("{0}=\"{1}\"", attrName, attrVal);
                } else if (attrName == "style") {
                    // FIXME: Special handling for css
                }
            }
            if (attributeStringBuilder.Length > 0)
                attributeStringBuilder.Insert(0, " ");
            return attributeStringBuilder.ToString();
        }
 private void WriteTranslatedText(HtmlNode node, string text)
 {
     if (node.NodeType == HtmlNodeType.Text)
     {
         node.InnerHtml = text;
     }
     else if (node.NodeType == HtmlNodeType.Element && node.Name.ToLower() == "input")
     {
         node.SetAttributeValue("value", text);
     }
 }
Exemple #8
0
 private static void TranslateUrlAttribute(HtmlNode node, string attrName, string oldBaseUrl, string newBaseUrl)
 {
     if (node != null)
     {
         string url = node.GetAttributeValue(attrName, null);
         if (!url.IsNullOrWhitespace())
         {
             url = url.Trim();
             if (!url.Contains(':') && !url.StartsWith("/", StringComparison.InvariantCultureIgnoreCase))
             {
                 string absUrl = Utils.CombineUrls(oldBaseUrl, url);
                 if (!absUrl.StartsWith(".."))
                 {
                     string newRelUrl = Utils.MakeRelativeUrl(newBaseUrl, absUrl);
                     node.SetAttributeValue(attrName, newRelUrl);
                 }
             }
         }
     }
 }
Exemple #9
0
        /// <summary>
        /// Takes a list of css declarations, like color:white, and puts them in the element's style attribute.  Certain cases are treated special.
        /// </summary>
        /// <param name="element"></param>
        /// <param name="declarations"></param>
        /// <remarks>
        /// Special Cases:
        /// img: width & height attributes
        /// td: align & valign
        /// table: cellspacing, border, and padding
        /// </remarks>
        public static void InlineDeclarations(HtmlNode element, List<CssDeclaration> declarations)
        {
            HtmlAttribute style = element.Attributes["style"];
            StringBuilder styleVal = null;
            HashSet<string> existingStyles = null; //so we don't overwrite any preexisting inline styles
            if (style != null)
            {
                existingStyles =
                    new HashSet<string>(CssParser.ParseDeclarations(style.Value).Select(dec => dec.Property));
                if (existingStyles.Count > 0)
                {
                    styleVal = new StringBuilder(style.Value.Trim());
                    if (styleVal[styleVal.Length - 1] != ';')
                        styleVal.Append(';');
                }
            }

            string tagName = element.Name.ToLowerInvariant();
            foreach (var declaration in declarations)
            {
                if (existingStyles != null && existingStyles.Contains(declaration.Property))
                    continue; //ignore the duplicate

                if (tagName.EqualsCaseInsensitive("td"))
                {
                    if (declaration.Property.EqualsCaseInsensitive(CssProperties.TextAlign))
                    {
                        if (!InlineNonStyleAttribute(element, "align", declaration.Value))
                            continue;
                    }
                    else if (declaration.Property.EqualsCaseInsensitive(CssProperties.VerticalAlign))
                    {
                        if (!InlineNonStyleAttribute(element, "valign", declaration.Value))
                            continue;
                    }
                }

                if (tagName.EqualsAny("table", "td", "img") &&
                    declaration.Property.EqualsAny(CssProperties.Width, CssProperties.Height))
                {
                    if (!InlineNonStyleAttribute(element, declaration.Property, declaration.Value))
                        continue;
                }
                if (tagName.EqualsAny("table") && declaration.Property.EqualsAny(CssProperties.BackgroundColor))
                {
                    if (!InlineNonStyleAttribute(element, "bgcolor", declaration.Value))
                        continue;
                }

                //a nice way to auto insert cellpadding and cellspacing
                if (declaration.Property.StartsWith("-attr-"))
                {
                    InlineNonStyleAttribute(element, declaration.Property.Strip("-attr-"), declaration.Value);
                    continue;
                }
                if (styleVal == null)
                    styleVal = new StringBuilder();

                styleVal.Append(declaration.Property + ":" + declaration.Value + ";");
            }

            if (styleVal != null)
                element.SetAttributeValue("style", styleVal.ToString());
        }
		void RemoveDefaultStyles(HtmlNode node) {
			var attrStyle = node.Attributes["style"];
			if (null == attrStyle) { return; }

			var strStyle = attrStyle.Value;
			if (string.IsNullOrWhiteSpace(strStyle)) { return; }

			var parts = strStyle.Split(';');
			var allowedStyleParts = new List<string>();
			var removedStylePartsCounter = 0;
			foreach (var part in parts) {
				allowedStyleParts.Add(part);
				var subParts = part.Split(':');
				if (2 != subParts.Length) { continue; }

				var key = subParts[0];
				string defaultValue;
				if (!DefaultStyles.TryGetValue(key, out defaultValue)) {
					continue;
				}

				var styleValue = subParts[1];
				defaultValue = defaultValue.Trim();
				if (0 != string.Compare(styleValue, defaultValue, StringComparison.InvariantCultureIgnoreCase)) {
					continue;
				}

				allowedStyleParts.Remove(part);
				removedStylePartsCounter++;
			}

			if (removedStylePartsCounter > 0) {
				var newStyleValue = string.Join(";", allowedStyleParts);
				node.SetAttributeValue("style", newStyleValue);
			}
		}
		void TransformFormatingSpansToFormatingElements(HtmlNode node) {
			if (false == node.IsAnyTag("span", "p")) { return; }

			var style = ParseStyle(node);
			if (style.Count < 1) { return; }

			var wasTransformed = false;
			var parentChildren = node.ParentNode.ChildNodes;
			Action<string> wrapSpan = (wrapperTagName) => {
				var wrapperNode = HtmlNode.CreateNode("<" + wrapperTagName + "></" + wrapperTagName + ">");
				wrapperNode.InnerHtml = node.InnerHtml;
				node.InnerHtml = wrapperNode.OuterHtml;
				wasTransformed = true;
			};
			Action<string, string, string> wrapSpanByStyle = (key, value, wrapperTagName) => {
				var styleValue = style.Find(key);
				styleValue = null != styleValue ? styleValue.Trim() : string.Empty;

				if (styleValue.InvEquals(value.Trim())) {
					wrapSpan(wrapperTagName);
					style.Remove(key);
				}
			};

			wrapSpanByStyle("font-weight", "bold", "b");
			wrapSpanByStyle("font-style", "italic", "i");
			wrapSpanByStyle("text-decoration", "underline", "u");

			if (false == wasTransformed) { return; }

			if (style.Count < 1) {
				node.Attributes.Remove("style");
			}
			else {
				var finalStyle = ComposeStyle(style);
				node.SetAttributeValue("style", finalStyle);
			}
		}
        public void PopulateIssueInfoNode(HtmlNode issueInfoNode, HtmlNode kesiNode, HtmlNode mdNode)
        {
            string status = GetNodeInnerText(kesiNode, "./s:issueStatus", null);
            if (status != null)
                issueInfoNode.SetAttributeValue("status", status.EncodeXMLString());
            string resolution = GetNodeInnerText(kesiNode, "./s:issueResolution", null);
            if (resolution != null)
                issueInfoNode.SetAttributeValue("resolution", resolution.EncodeXMLString());
            string productName = GetNodeInnerText(kesiNode, "./s:issueProduct/s:productId", null);
            if (productName != null && GetNodeInnerText(kesiNode, "./s:issueActivity/s:activityWhat", "Product") == "Product")
                issueInfoNode.SetAttributeValue("productName", productName.EncodeXMLString());
            string componentName = GetNodeInnerText(kesiNode, "./s:issueProduct/s:productComponentId", null);
            if (componentName != null && GetNodeInnerText(kesiNode, "./s:issueActivity/s:activityWhat", "Component") == "Component")
                issueInfoNode.SetAttributeValue("componentName", componentName.EncodeXMLString());

            string priority = GetNodeInnerText(kesiNode, "./s:issuePriority", null);
            if (priority != null)
                issueInfoNode.SetAttributeValue("priority", priority.EncodeXMLString());
            string severity = GetNodeInnerText(kesiNode, "./s:issueSeverity", null);
            if (severity != null)
                issueInfoNode.SetAttributeValue("severity", severity.EncodeXMLString());

            string systemOS = GetNodeInnerText(kesiNode, "./s:issueComputerSystem/s:computerSystemOS", null);
            if (systemOS != null)
                issueInfoNode.SetAttributeValue("systemOS", systemOS.EncodeXMLString());
            string systemPlatform = GetNodeInnerText(kesiNode, "./s:issueComputerSystem/s:computerSystemPlatform", null);
            if (systemPlatform != null)
                issueInfoNode.SetAttributeValue("systemPlatform", systemPlatform.EncodeXMLString());
            string productVersion = GetNodeInnerText(kesiNode, "./s:issueProduct/s:productVersion", null);
            if (productVersion != null)
                issueInfoNode.SetAttributeValue("productVersion", productVersion.EncodeXMLString());

            string assignedToName = GetIssueAssignedTo(kesiNode);
            string assignedToUri = GetNodeInnerText(mdNode, "./o:issueAssignedToUri", null);
            if (!string.IsNullOrEmpty(assignedToName)) {
                HtmlNode assignedToNode = issueInfoNode.OwnerDocument.CreateElement("assignedTo");
                issueInfoNode.AppendChild(assignedToNode);
                assignedToNode.SetAttributeValue("name", assignedToName.EncodeXMLString());
                if (!string.IsNullOrEmpty(assignedToUri))
                    assignedToNode.SetAttributeValue("uri", assignedToUri.EncodeXMLString());
            }
            string CCName = GetIssueCCPerson(kesiNode);
            string CCUri = GetNodeInnerText(mdNode, "./o:issueCCPerson", null);		// todo: change this to the right value
            if (!string.IsNullOrEmpty(CCName)) {
                HtmlNode assignedToNode = issueInfoNode.OwnerDocument.CreateElement("CC");
                issueInfoNode.AppendChild(assignedToNode);
                assignedToNode.SetAttributeValue("name", CCName.EncodeXMLString());
                if (!string.IsNullOrEmpty(CCUri))
                    assignedToNode.SetAttributeValue("uri", CCUri.EncodeXMLString());
            }
        }
Exemple #13
0
 public static HtmlNode SetClassName(this HtmlNode node, string className)
 {
     node.SetAttributeValue("class", className);
     return(node);
 }
        public override string HandleObjects(HtmlNode node)
        {
            if (node != null)
            {
                // shrink window to 75% of page; 50% if in quotes
                node.SetAttributeValue("width", isInQuoteBlock ? "160" : "240");
                node.SetAttributeValue("height", isInQuoteBlock ? "120" : "180");
            }

            return node.OuterHtml;
        }
        private void SetLinkCssClass(HtmlNode wikiLink)
        {
            var href = wikiLink.GetAttributeValue("href", null) ?? string.Empty;

            int hashIndex = href.IndexOf('#');
            href = (hashIndex >= 0) ? href.Substring(0, hashIndex) : href;

            string linkArticle = (string.IsNullOrWhiteSpace(href) || href == this.wikiSlashUrlPrefix)
                                     ? WikiDownConfig.WikiIndexArticleSlug
                                     : this.wikiLinkPrefixRemoveRegex.Replace(href, string.Empty).TrimEnd('/');

            var articleSlugExists = this.articleExistsHelper.GetExists(linkArticle);
            if (!articleSlugExists)
            {
                wikiLink.SetAttributeValue("class", ArticleExistsHelper.NoArticleCssClass);
            }
        }
Exemple #16
0
        public void XslToHTML()
        {
            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(styleSheetFile);
            transform.Transform(xmlFile, HttpContext.Current.Server.MapPath("/tmp") + "/Formulario.html");
            htmlDoc.Load("C:\\Form1\\Formulario.html");
            foreach (HtmlNode node in htmlDoc.DocumentNode.SelectNodes("//span[@class='xdTextBox']"))
            {
                node.Name = "input";
            }

            foreach (HtmlNode node in htmlDoc.DocumentNode.SelectNodes("//div[@class='xdDTPicker']"))
            {
                node.Name = "input";
                foreach (HtmlNode node2 in node.ChildNodes)
                {
                    if (node2.Name.Equals("span"))
                    {
                        node.SetAttributeValue("xd:binding", node2.Attributes["xd:binding"].Value);
                        node.SetAttributeValue("onclick", "setFecha(this)");
                    }
                }
                node.RemoveAllChildren();
                HtmlAttribute attr = htmlDoc.CreateAttribute("type", "date");
                node.Attributes.Prepend(attr);
                node.SetAttributeValue("style", "width: 100%;");

                node.SetAttributeValue("onclick", "setFecha(this)");

            }
            foreach (HtmlNode node in htmlDoc.DocumentNode.SelectNodes("//input | //select"))
            {
                node.SetAttributeValue("id", (idCounter++).ToString());
                if (node.Attributes["type"]!=null &&node.Attributes["type"].Value.Equals("button"))
                {
                    node.SetAttributeValue("onclick", "save()");
                }
            }

            HtmlNode head = htmlDoc.DocumentNode.SelectSingleNode("//head");
            HtmlNode body = htmlDoc.DocumentNode.SelectSingleNode("//body");
            HtmlNode meta = new HtmlNode(HtmlNodeType.Element, htmlDoc, nodeIndex++);
            HtmlNode script = new HtmlNode(HtmlNodeType.Element, htmlDoc, nodeIndex++);

            script = new HtmlNode(HtmlNodeType.Element, htmlDoc, nodeIndex++);
            script.Name = "script";
            script.Attributes.Add("type", "text/javascript");
            script.SetAttributeValue("src", "tmp.js");
            head.ChildNodes.Add(script);

            meta.Name = "meta";
            meta.Attributes.Add("content", "width=device-width");
            head.ChildNodes.Add(meta);
            meta = new HtmlNode(HtmlNodeType.Element, htmlDoc, nodeIndex++);
            meta.Name = "meta";
            meta.Attributes.Add("property", "maxid");
            meta.Attributes.Add("content", idCounter.ToString());
            head.ChildNodes.Add(meta);

            HtmlNode link = new HtmlNode(HtmlNodeType.Element, htmlDoc, nodeIndex++);
            link.Name = "link";
            link.Attributes.Add("href", "common/bootstrap-responsive.min.css");
            head.ChildNodes.Add(link);
            foreach (HtmlNode node in htmlDoc.DocumentNode.SelectNodes("//body/div"))
            {
                node.Attributes.Add("class", "row-fluid");
            }
            this.addSpan(htmlDoc);

            htmlDoc.Save("C:\\Form1\\Formulario.html");
            idCounter = 0;
        }
Exemple #17
0
        private static void ApplyOutlineCssToHtmlNode(HtmlNode node, Dictionary<string, string> outlineStyle)
        {
            string inlineStyle = node.GetAttributeValue("style", String.Empty);
            Dictionary<string, string> inlineStyleAsDictionary = ConvertStyleToDictionary(inlineStyle);

            AddOutlineStylesToInlineStyles(inlineStyleAsDictionary, outlineStyle);

            string mergedCss = string.Join(";", inlineStyleAsDictionary.Select(x => string.Format("{0}:{1}", x.Key, x.Value)).ToArray());

            node.SetAttributeValue("style", mergedCss);
        }
 private static void UpdateSingleHref(HtmlNode node, string attributeName, string filePath)
 {
     var href = node.GetAttributeValue(attributeName, string.Empty);
     if (PathUtility.IsRelativePath(href))
         node.SetAttributeValue(attributeName, RebaseHref(href, filePath, string.Empty));
 }
        private static ModifyStatus ModifyLink(HtmlNode element, string attribName, string outputDir, string filesDirName)
        {
            string attribValue = element.GetAttributeValue(attribName, null);
            if (attribValue == null)
            {
                return ModifyStatus.Ignored;
            }

            string attribValueLower = attribValue.ToLowerInvariant();
            if (attribValueLower.StartsWith("http://") || attribValueLower.StartsWith("https://"))
            {
                // downloadable!
                var downloadRequest = (HttpWebRequest)WebRequest.Create(attribValue);
                downloadRequest.Timeout = 5000;

                WebResponse downloadResponse;
                try
                {
                    downloadResponse = downloadRequest.GetResponse();
                }
                catch (WebException)
                {
                    // this failed; continue with the next image
                    return ModifyStatus.Failure;
                }

                byte[] imageData;
                string mimeType;

                using (downloadResponse)
                using (var responseHolder = new MemoryStream())
                {
                    downloadResponse.GetResponseStream().CopyTo(responseHolder);
                    mimeType = downloadResponse.Headers[HttpResponseHeader.ContentType] ?? "application/octet-stream";
                    imageData = responseHolder.ToArray();
                }

                string base64ImageData = Convert.ToBase64String(imageData);
                var imgDataUri = $"data:{mimeType};base64,{base64ImageData}";

                element.SetAttributeValue(attribName, imgDataUri);
                return ModifyStatus.Success;
            }

            if (attribValueLower.StartsWith(filesDirName))
            {
                byte[] fileData;
                string mimeType = "application/octet-stream";

                string inputFileName = Path.Combine(outputDir, attribValue.Replace('/', Path.DirectorySeparatorChar));
                using (var inputFile = new FileStream(inputFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (var contentHolder = new MemoryStream())
                {
                    inputFile.CopyTo(contentHolder);
                    fileData = contentHolder.ToArray();
                }

                string base64FileData = Convert.ToBase64String(fileData);
                var fileDataUri = $"data:{mimeType};base64,{base64FileData}";

                element.SetAttributeValue(attribName, fileDataUri);

                // try to delete original
                File.Delete(inputFileName);

                return ModifyStatus.Success;
            }

            return ModifyStatus.Ignored;
        }
		void RemoveOverlappingSpanInParagraph(HtmlNode parent) {
			if (0 != string.Compare(parent.Name, "p", StringComparison.InvariantCultureIgnoreCase)) { return; }

			if (parent.ChildNodes.Count != 1) {
				return;
			}

			var child = parent.ChildNodes[0];
			if (0 != string.Compare(child.Name, "span", StringComparison.InvariantCultureIgnoreCase)) { return; }

			if (child.Attributes.Count > 1) { return; }

			var attr0 = child.Attributes[0];
			if (0 != string.Compare(attr0.Name, "style", StringComparison.InvariantCultureIgnoreCase)){ return; }

			var parentStyle = ParseStyle(parent);
			var spanStyle = ParseStyle(attr0.Value);
			foreach (var kp in spanStyle) {
				parentStyle[kp.Key] = kp.Value;
			}

			var finalStyle = ComposeStyle(parentStyle);
			parent.SetAttributeValue("style", finalStyle);
			parent.InnerHtml = child.InnerHtml;
		}
 private void ProcessTag(HtmlNode item, string tag, string att)
 {
     if (item.Name.EqualsIgnoreCase(tag))
     {
         String src = item.GetAttributeValue(att, null);
         if (src != null)
         {
             item.SetAttributeValue(att, ToAbsolute(src));
             
         }
     }
 }
        static private void start_Operation()
        {
            while (true)
            {
                if (file_Paths.Count == 0)
                {
                    System.Threading.Thread.Sleep(1000);
                }
                else
                {
                    try
                    {
                        //System.Threading.Interlocked.Increment(ref word_Application_Count);

                        while (file_Paths.Count > 0)
                        {
                            string temp_String = "";
                            if (file_Paths.TryDequeue(out temp_String))
                            {
                                string[] temp_Collection       = temp_String.Split(new string[] { "|^|" }, StringSplitOptions.None);
                                string   file_Path             = temp_Collection[0];
                                string   web_Page_Base_Address = temp_Collection[1];
                                string   folder_Path           = file_Path.Substring(0, file_Path.LastIndexOf("\\"));
                                string   file_Name             = file_Path.Substring(file_Path.LastIndexOf("\\") + 1);
                                if (!System.IO.File.Exists(file_Path))
                                {
                                    return;// continue;
                                }
                                string file_Name_Htm = folder_Path + "\\HTML\\" + System.IO.Path.ChangeExtension(file_Name, "htm");
                                if (System.IO.File.Exists(file_Name_Htm))
                                {
                                    return;// continue;
                                }
                                Microsoft.Office.Interop.Word._Document doc = app.Documents.Open(file_Path, Visible: false);
                                //Console.WriteLine(file_Name_Htm);
                                doc.SaveAs(FileName: file_Name_Htm, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML);
                                System.Threading.ThreadPool.QueueUserWorkItem((state) => {
                                    HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();

                                    // There are various options, set as needed
                                    htmlDoc.OptionFixNestedTags = true;

                                    // filePath is a path to a file containing the html
                                    //string filePath = @"C:\Documents and Settings\prabhakaran\Desktop\rv_3b72167e18a54fe28a330c5fbecc222f.htm";
                                    string filePath = file_Name_Htm;
                                    while (true)
                                    {
                                        try
                                        {
                                            htmlDoc.Load(filePath);
                                            break;
                                        }
                                        catch (Exception excp)
                                        {
                                        }
                                    }

                                    // Use:  htmlDoc.LoadXML(xmlString);  to load from a string

                                    // ParseErrors is an ArrayList containing any errors from the Load statement
                                    if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
                                    {
                                        // Handle any parse errors as required
                                    }
                                    else
                                    {
                                        if (htmlDoc.DocumentNode != null)
                                        {
                                            HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");

                                            if (bodyNode != null)
                                            {
                                                bodyNode.SetAttributeValue("onload", "var temp_Element_Pdf = document.getElementById('PDF Link');temp_Element_Pdf.style.width=screen.width/2;temp_Element_Pdf.style.height='50';var temp_Element_Doc = document.getElementById('DOC Link');temp_Element_Doc.style.width=screen.width/2;temp_Element_Doc.style.height='50';temp_Element_Doc.style.position='absolute';");

                                                HtmlNode pdf_Link = htmlDoc.CreateElement("button"); //new HtmlNode(HtmlNodeType.Element, htmlDoc, 0);
                                                pdf_Link.SetAttributeValue("value", "PDF");
                                                pdf_Link.SetAttributeValue("id", "PDF Link");
                                                string pdf_Path = web_Page_Base_Address + "Local_Database/PDF/" + System.IO.Path.ChangeExtension(file_Name, "pdf");
                                                pdf_Link.SetAttributeValue("onclick", "window.open('" + pdf_Path + "','_blank','location=no,menubar=no,status=no,toolbar=no');");
                                                pdf_Link.InnerHtml = "PDF";
                                                pdf_Link.SetAttributeValue("style", "background-color:#262626;color:#747474;border-style:groove;border-color:#121212;-moz-appearance:none;");
                                                pdf_Link.SetAttributeValue("onmouseover", "this.style.backgroundColor='#262626';this.style.color='#adbdde';this.style.fontWeight='bold';this.style.fontSize='normal';this.style.borderColor='#afafaf';");  //#afafaf
                                                pdf_Link.SetAttributeValue("onmouseout", "this.style.backgroundColor='#262626';this.style.color='#747474';this.style.fontWeight='normal';this.style.fontSize='normal';this.style.borderColor='#121212';");
                                                bodyNode.ChildNodes.Add(pdf_Link);

                                                HtmlNode doc_Link = htmlDoc.CreateElement("button"); //new HtmlNode(HtmlNodeType.Element, htmlDoc, 0);
                                                doc_Link.SetAttributeValue("value", "DOC");
                                                doc_Link.SetAttributeValue("id", "DOC Link");
                                                string doc_Path = web_Page_Base_Address + "Local_Database/DOC/" + System.IO.Path.ChangeExtension(file_Name, "doc");
                                                doc_Link.SetAttributeValue("onclick", "window.open('" + doc_Path + "','_blank','location=no,menubar=no,status=no,toolbar=no');");
                                                doc_Link.InnerHtml = "DOC";
                                                doc_Link.SetAttributeValue("style", "background-color:#262626;color:#747474;border-style:groove;border-color:#121212;-moz-appearance:none;");
                                                doc_Link.SetAttributeValue("onmouseover", "this.style.backgroundColor='#262626';this.style.color='#adbdde';this.style.fontWeight='bold';this.style.fontSize='normal';this.style.borderColor='#afafaf';");  //#afafaf
                                                doc_Link.SetAttributeValue("onmouseout", "this.style.backgroundColor='#262626';this.style.color='#747474';this.style.fontWeight='normal';this.style.fontSize='normal';this.style.borderColor='#121212';");
                                                bodyNode.ChildNodes.Add(doc_Link);

                                                //htmlDoc.Save(@"C:\Documents and Settings\prabhakaran\Desktop\new.html");
                                                htmlDoc.Save(file_Name_Htm);

                                                // Do something with bodyNode
                                            }
                                        }
                                    }// ***
                                });


                                string file_Name_Pdf = folder_Path + "\\PDF\\" + System.IO.Path.ChangeExtension(file_Name, "pdf");
                                //Console.WriteLine(file_Name_Pdf);
                                doc.SaveAs(FileName: file_Name_Pdf, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
                                //Console.WriteLine(folder_Path + "\\DOC\\" + file_Name);
                                ((Microsoft.Office.Interop.Word._Document)doc).Close(SaveChanges: Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges);
                                while (true)
                                {
                                    try
                                    {
                                        System.IO.File.Move(file_Path, folder_Path + "\\DOC\\" + file_Name);
                                        break;
                                    }
                                    catch (Exception excp)
                                    {
                                    }
                                }
                            }
                        }
                        //System.Threading.Interlocked.Decrement(ref word_Application_Count);
                    }
                    catch (Exception excp)
                    {
                        Console.WriteLine(excp.Message);
                    }
                }
            }
        }
Exemple #23
0
        private static bool InlineNonStyleAttribute(HtmlNode element, string attributeName, string value)
        {
            HtmlAttribute att = element.Attributes[attributeName];
            if (att != null && att.Value.HasChars())
                return false;

            element.SetAttributeValue(attributeName, value);
            return true;
        }