当前上下文中不存在名称fonts - XMLWorker错误

时间:2018-04-05 16:42:42

标签: c# itext xmlworker

我看到了一些关于如何在XMLWorker中使用字体的链接,但不幸的是,它们没有解决我的问题。

在下面发布的代码中,我遇到错误"当前上下文中不存在名称字体"

StringReader sr = new StringReader(body.ToString());

Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
iTextSharp.tool.xml.pipeline.css.ICSSResolver CSSResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
using (MemoryStream memoryStream = new MemoryStream())
{
    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
   // iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
   //  new System.IO.FileStream(System.IO.Directory.GetCurrentDirectory() + "\\ScienceReport.pdf",
   //System.IO.FileMode.Create));
    pdfDoc.Open();

    var xmlWorkerHelper = XMLWorkerHelper.GetInstance();
    var cssResolver = new StyleAttrCSSResolver();
    var xmlWorkerFontProvider = new XMLWorkerFontProvider();
    IEnumerable<string> fonts = null;
    foreach (string font in fonts)
    {
        xmlWorkerFontProvider.Register(font);
    }
    var cssAppliers = new CssAppliersImpl(xmlWorkerFontProvider);
    var htmlContext = new HtmlPipelineContext(cssAppliers);
    htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
    PdfWriterPipeline pdfWriterPipeline = new PdfWriterPipeline(pdfDoc, writer);
    HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, pdfWriterPipeline);
    CssResolverPipeline cssResolverPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
    XMLWorker xmlWorker = new XMLWorker(cssResolverPipeline, true);
    //htmlparser.Parse(sr);
    XMLParser xmlParser = new XMLParser(xmlWorker);
    pdfDoc.Close();
    byte[] bytes = memoryStream.ToArray();
    memoryStream.Close();

错误位于 FOR EACH 循环内。

有任何想法如何解决此错误?

我在这里找到的一些片段是在SO上找到的。

0 个答案:

没有答案