Cannot Get CSS to Work in Itextsharp (5.4.3) When Making Pdf

Cannot get CSS to work in iTextSharp (5.4.3) when making pdf

Well it would appear that the CSS was correctly being applied as I tested a

td{
border:1px solid red;
padding:0.4em;
margin:0;
}

to the pdf, and all the cells got bordered in red, so it would appear that the pdf overrides certain styles. Not sure why.

Not applying the CSS while generating PDF using iTextsharp.dll

There's a couple of things going on here. First and foremost, the HTML/CSS parser in iText and iTextSharp are far from complete. They're definitely very powerful but still have a ways to go. Each version gets better so always make sure that you're using the latest version.

Second, I've seen more HTML/CSS activity in an add-on for iText/iTextSharp called XMLWorker that you might want to look at. You don't "load styles" anymore, you just pass raw HTML/CSS in and it figures out a lot of things. You can see some examples here, see a list of supported CSS attributes here, download it here (and get the two missing files here and here).

Third, LoadTagStyle is for loading style attributes for HTML tags, not CSS IDs or Classes. You want to use LoadStyle to load by class:

styles.LoadStyle("<classname>", "<attribute>", "<value>");

Unfortunately this method still doesn't do what you want it to do always. For instance, to change the font size you'd think you'd say:

styles.LoadStyle("headerdiv", "font-size", "60ptx);

But to get it to work you can only use relative HTML font sizes (1,2,-1, etc) or PT sizes and you must use the size property:

styles.LoadStyle("headerdiv", "size", "60pt");
//or
styles.LoadStyle("headerdiv", "size", "2");

The LoadStyle honestly feels like an afterthought that was only partially completed and I recommend not using it actually. Instead I recommend writing the style attributes directly inline if you can:

string html = "<div id=\"personal\" class=\"headerdiv\" style=\"padding-left:50px;font-size:60pt;font-family:Cambria;font-weight:700;\">Personal Data</div>";

Obviously this defeats the points of CSS and once again, that's why they're working on the new XMLWorker above.

Lastly, to use fonts by name you have to register them with iTextSharp first, it won't go looking for them:

iTextSharp.text.FontFactory.Register(@"c:\windows\fonts\cambria.ttc", "Cambria");

itextSharp not apply html style attributes

Your problem is the CSS attribute you are using, XMLWorker doesn't support left, bottom, z-index, only partially height

You can check the support of every CSS attribute from this list

iTextSharp external stylesheet

That looks like its using HtmlToPdfBuilder which is not from the makers of iText or iTextSharp but might still work for you.

[EDIT]

Dead link removed, used to be http://somewebguy.wordpress.com/tag/itextsharp/



Related Topics



Leave a reply



Submit