My Text

Applying a style to a div with the iTextSharp class name

I defined my html line as:

string html = @" <html><body> <div class='class1'>My Text</div> </body></html> "; 

To apply the style, I do it

 StyleSheet style = new StyleSheet(); style.LoadTagStyle("class1", HtmlTags.FACE , "PATH" + "CustomFont.ttf"); 

This does not work. However, using this, the font is applied:

  style.LoadTagStyle(HtmlTags.DIV, HtmlTags.FACE , "PATH"+"CustomFont.ttf"); 

How to specify a style for a particular class? I am creating pdf using iTextSharp dll.

0
itextsharp
Jan 14 '14 at 5:34
source share
1 answer

You need to create an instance of the class that implements the IFontProvider instance. XMLWorker comes with a class that already implements this, so you can simply use the XMLWorkerFontProvider class and register your fonts. The second parameter to the Register() method is optional, but I recommend that you use it to explicitly specify the font as an alias.

After that, you can use the long ParseXHtml() form, which takes streams for both HTML and CSS. If you are loading one of these two from disk, you should check the encodings.

The following is a complete working example tested against iTextSharp and XMLWorker 5.2.4. See Comments for more details.

 //File to output var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf"); //Standard PDF setup, nothing special here using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) { using (var doc = new Document()) { using (var writer = PdfWriter.GetInstance(doc, fs)) { //Open our document for writing doc.Open(); //Our basic HTML var html = @"<html><body><div class=""class1"">My Text</div></body></html>"; //Fully qualified path to our font var myFont = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ALGER.TTF"); //Register our font and give it an alias to reference in CSS var fontProv = new XMLWorkerFontProvider(); fontProv.Register(myFont, "AlgerianRegular"); //Create our CSS var css = @".class1{font-family: AlgerianRegular; color: #f00; font-size: 60pt;}"; //Create a stream to read our HTML using (var htmlMS = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html))) { //Create a stream to read our CSS using (var cssMS = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(css))) { //Get an instance of the generic XMLWorker var xmlWorker = XMLWorkerHelper.GetInstance(); //Parse our HTML using everything setup above xmlWorker.ParseXHtml(writer, doc, htmlMS, cssMS, System.Text.Encoding.UTF8, fontProv); } } //Close and cleanup doc.Close(); } } } 
0
Jan 16 '14 at 15:16
source share



All Articles