用iTextSharp中的XML Worker替换HTMLWorker

时间:2013-05-24 15:16:29

标签: c# itextsharp

目前我正在使用此代码:

StyleSheet css = new StyleSheet();
using (var htmlViewReader = new StringReader(htmlText)) {
    using (var htmlWorker = new HTMLWorker(pdfDocument)) {
        css.LoadStyle("body", "style", "width: 100%;");
        //  css.LoadStyle(".fr", "style", "float: right;");
        css.LoadStyle("fr","float","right");
        css.LoadStyle(".fl", "style", "float: left; width: 20%;");
        css.LoadStyle("container", "style", "width: 960px; margin: 0 auto;");
        css.LoadStyle("header", "style", "margin-top: 75px; width: 100%;");
        css.LoadStyle("header name", "style", "font-size: 18px;");
        css.LoadStyle("footer", "style", "border-top: 2px solid #333; text-align: center;");
        css.LoadTagStyle("p", "style", "padding: 0 45px 0 25px; color: #666;");
        css.LoadTagStyle("a", "style", "color: #666;");
        css.LoadStyle("deposit", "style", "font-size: 22px; width: 100%; color: #999; font-weight: bold; float:right;");
        css.LoadStyle("cl", "style", "clear: both;");
        css.LoadStyle("title", "style", "margin: 0 45px 0 25px; border-bottom: 2px solid #333; font-weight: bold;");
        css.LoadTagStyle("ul", "style", "list-style-type: none; width: 50%;");
        css.LoadTagStyle("ul li", "style", "line-height: 25px;");
        css.LoadTagStyle("li", "style", "line-height: 25px;");
        htmlWorker.SetStyleSheet(css);
        //htmlWorker.Parse(htmlViewReader);
    }
}

但是,正如文档HTMLWorker不解析CSS样式。

我需要用XML Worker替换它。关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:1)

要将CSS与XML Worker一起使用,您可以从外部css文件加载它:

public static class XMLWorkerUtils
{
    public static ICssFile GetCssFile(string filePath)
    {
        using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            return XMLWorkerHelper.GetCSS(stream);
        }
    }
}

或者您可以内联定义:

var cssResolver = new StyleAttrCSSResolver();
// cssResolver.AddCss(XMLWorkerUtils.GetCssFile(@"c:\path\pdf.css"));
cssResolver.AddCss(@"code
                         {
                            padding: 2px 4px;
                            color: #d14;
                            white-space: nowrap;
                            background-color: #f7f7f9;
                            border: 1px solid #e1e1e8;
                         }",
                         "utf-8", true);

然后将此cssResolver注入CssResolverPipeline。请在its official documentation here中了解详情。