ITextSharp:指定HTML类或ID CSS

saz*_*azr 1 html css c# itext

我正在使用ITextSharp将一些HTML转换为.pdf文件.

是否可以在ITextSharp中设置类css,还是只能设置HTML元素CSS?

例如:如果我转换以下HTML

<p class="redBigText">test</p>
Run Code Online (Sandbox Code Playgroud)

我可以创建一个ITextSharp StyleSheet对象并为类redBigText指定CSS 吗?

StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
styles.LoadTagStyle(".redBigText", "font-size", "50px");
styles.LoadTagStyle(".redBigText", "color", "#ff0000");
var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(mainContents), styles);
Run Code Online (Sandbox Code Playgroud)

或者我只能在ITextSharp中设置CSS元素吗?

StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
styles.LoadTagStyle("P", "font-size", "50px");
styles.LoadTagStyle("P", "color", "#ff0000");
var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(mainContents), styles);
Run Code Online (Sandbox Code Playgroud)

kuu*_*nbo 6

是的,您可以指定一个CSS类名:

string Html = @"
<h1>h1</h1>
<p>Default paragraph</p>  
<p class='redBigText'>A paragraph with CSS class</p>  
";
StyleSheet styles = new StyleSheet();
styles.LoadStyle("redBigText", "size", "20pt");
styles.LoadStyle("redBigText", "color", "#ff0000");
Run Code Online (Sandbox Code Playgroud)

在这里记录.

遗憾的是,您无法指定id属性.还要注意,如果你混合和匹配LoadTagStyle()LoadStyle()调用,那么LoadTagStyle()胜利.例如:

StyleSheet styles = new StyleSheet();
styles.LoadTagStyle("p", "size", "10pt");
styles.LoadTagStyle("p", "color", "#0000ff");     
styles.LoadStyle("redBigText", "size", "20pt");
styles.LoadStyle("redBigText", "color", "#ff0000");
Run Code Online (Sandbox Code Playgroud)

这里所有段落都是蓝色和10pt.