我已经从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>
正如文档所述,我在 head 标签内插入了指向 css 文件的链接。
提前致谢