65.9K
CodeProject 正在变化。 阅读更多。
Home

一个简单的 HTML 构建器实用程序类

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.52/5 (34投票s)

2006年3月19日

2分钟阅读

viewsIcon

79164

downloadIcon

1039

当你的应用程序对文本的 HTML 格式化要求(例如:打印页面、电子邮件文本等)比较简单时,这个简单的构建工具类将节省你的开发时间。

Sample Image - HTML_Build_Clss.png

引言

 

在开发基于 Web 的应用程序时,你需要将一些文本转换为 HTML 标签以获得方便的格式。这在需要发送电子邮件或在“打印”页面上显示文本时尤其需要。当然,Web 上有很多可用的工具类和工具。但幸运的是,我的应用程序对 HTML 文本的要求非常简单,而且不幸的是,我没有找到任何简单的 HTML 构建工具来格式化我的简单文本。然而,像往常一样,我决定编写一个易于使用的工具类。

 

使用该类

 

让我们看看使用我们的简化 HTML 构建工具类的示例代码。

public static void UseThis()
{
Ashraf.HTMLUtil util = new Ashraf.HTMLUtil();

util.AppendHeader("Header");
util.AppendSubHeader("Sub Header");
util.AppendPara("Hello this is a para");
util.AppendPara("Hello this is the second para");
util.AppendBlankRow();
util.FormatToRowInColonSeparatedText("Label 1","Value 1", false);
util.FormatToRowInColonSeparatedText("Label 2","Value 2", false);
util.AppendBlankRow();
util.AppendPara("Hello this is footer para");
util.AppendSubHeader("Sub Footer");
util.AppendHeader("Footer");

System.Web.HttpContext.Current.Response.Write(util.FormattedHTMLText);
}

 

首先,你需要创建“HTMLUtil”类的一个实例。然后,使用不同的方法,你可以将你的内容添加到这个实例中。内部,System.Text.StringBuilder 类实例是所有内容的容器,并以相应的格式进行存储。工具类的方法将所有内容包装在一个 html 表格中,以便可以将内容轻松地放置在任何位置。使用“HTMLUtil”实例,你可以添加标题、副标题、普通文本、空行等。

util.AppendHeader("Header");
util.AppendSubHeader("Sub Header");
util.AppendPara("Hello this is a para");
util.AppendBlankRow();

 

然而,如代码所示,有一个名为“FormatToRowInColonSeparatedText”的方法。此方法将冒号分隔的行附加到 System.Text.StringBuilder 容器中,并将传入的参数作为标题和值。当你想为数据库表字段格式化 html 时,这很有用。

 

util.FormatToRowInColonSeparatedText("Label 1","Value 1", false);

 

 

当你完成以所需格式构建文本时,你就可以使用它了。你将通过类的“FormattedHTMLText”属性获得所有以正确格式化的文本。

 

System.Web.HttpContext.Current.Response.Write(util.FormattedHTMLText);

 

然而,你可以通过以下属性定义标题、副标题、普通文本的字体大小以及构建工具类的字体样式。

 

public int HeaderTextSize{get;set;} //default size is 4 
public int SubHeaderTextSize{get;set;} //default size is 3 
public int NormalTextSize{get;set;} //default size is 2 
public string FontFace{get;set;} // default is "verdana"

 

结论

 

对于这个类,任何建议或更正都将不胜感激。

© . All rights reserved.