Applying style to div having a class name iTextSharp

前端 未结 1 852
日久生厌
日久生厌 2020-12-12 02:51

i have defined my html string as:

            string html = @\"
                    
                    
1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 03:19

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

    Once you have that you can use the long form of ParseXHtml() which takes streams for both the HTML and CSS. If you're loading either of these two from disk you should check the encodings.

    The below code is a full working example tested against iTextSharp and XMLWorker 5.2.4. See the comments for further 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 = @"
    My Text
    "; //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 讨论(0)
提交回复
热议问题