使用XMLWorker引用外部css文件

时间:2013-09-08 17:48:33

标签: pdf-generation itextsharp itext

我已从 HtmlWorker 切换到 XMLWorker ,以便充分利用的使用外部css文件。此外,通过这种方式,我避免使用内联样式。

这是我目前的代码:

public ActionResult ViewPdf(object model)
    {
        var doc = new Document(PageSize.A3, 10f, 1f, 10f, 30f);

        var memStream = new MemoryStream();
        var writer = PdfWriter.GetInstance(doc, memStream);
        writer.CloseStream = false;

        doc.Open();

        var xmltext = RenderActionResultToString(View(model));

        var htmlContext = new HtmlPipelineContext(null);
        htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

        var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
        cssResolver.AddCssFile(Server.MapPath("~/Content/StyleSheet1.css"), true);

        var pipeline = new CssResolverPipeline(cssResolver,
                                               new HtmlPipeline(htmlContext, new PdfWriterPipeline(doc, writer)));

        var worker = new XMLWorker(pipeline, true);
        var parser = new XMLParser(worker);

        using (var sr = new StringReader(xmltext))
        {

            parser.Parse(sr);
        }


        doc.Close();

        var buf = new byte[memStream.Position];
        memStream.Position = 0;
        memStream.Read(buf, 0, buf.Length);

        return new BinaryContentResult(buf, "application/pdf");
    }

RenderActionResultToString(View(model))正在给我要解析为pdf的字符串。一切正常。问题在于风格。如果我使用内联样式,例如:

<table style ="width: 400px">

,一切都像魅力一样。但如果我使用类似的东西:

<table class = "foo">

,并像这样引用一个css文件(StyleSheet1.css):

.foo {
    width: 400px;
}

,它不起作用......

我尝试在我正在解析的字符串中引用样式表,在我看来是这样的:

    <head>
        <link href ="@Server.MapPath("~/Content/StyleSheet1.css")" rel ="stylesheet" type="text/css"/>  
    </head>

我将链接插入到css文件中,就像documentation状态一样,在head标签内。

先谢谢

0 个答案:

没有答案