ITextSharp: Specify HTML Classes or ID CSS

老子叫甜甜 提交于 2019-12-23 01:45:27

问题


I am converting some HTML into a .pdf file using ITextSharp.

Is it possible to set a classes css in ITextSharp or can I only set HTML elements CSS?

For example: If I convert the following HTML

<p class="redBigText">test</p>

Can I create a ITextSharp StyleSheet object and specify the CSS for the class redBigText?

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);

Or can I only set CSS elements in ITextSharp?

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);

回答1:


Yes, you can specifiy a CSS class name:

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");

It's documented here.

Unfortunately you cannot specify id attributes. Also be aware that if you mix and match LoadTagStyle() and LoadStyle() calls, the LoadTagStyle() wins. For example:

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

Here, all paragraphs are blue and 10pt.




回答2:


although it is old post but might some one can get help by following solution.

You have to convert the following line

<p class="redBigText">test</p>

to

<p style="font-size : 50px;color : #ff0000">test</p>

itextsharp will now apply inline style to your html, it will not recognized css classes, as they are referenced from external file.

You can use This inline styles tool to convert you css classes to inline style.

  • Just copy the css from your classes to your html page.
  • copy the html to inliner tool.

You will get the inlined css html page. ~Happy Codding



来源:https://stackoverflow.com/questions/9612212/itextsharp-specify-html-classes-or-id-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!