iTextSharp XMLParser.Parse重复抛出并吞下异常

时间:2018-04-30 11:55:33

标签: c# itext

我有一个函数,我正在尝试给iTextSharp一些HTML,并从中生成PDF。此函数成功生成PDF,完成CSS样式,但运行速度不足以满足我们的要求。

我已经注意到一个特别需要花费很长时间才能执行的区域是对XMLParser.Parse的调用,我已经看到它需要花费14秒才能完成8页文档,只显示一个表格以图标为首的数据。在执行此方法期间,我注意到(在输出窗口中)iTextSharp或iTextSharp调用的代码抛出(并且可能被捕获)三个异常。这些例外是:

  1. ' System.Collections.Generic.KeyNotFoundException'在mscorlib.dll中
  2. ' iTextSharp.tool.xml.exceptions.NoDataException'在itextsharp.xmlworker.dll
  3. ' System.ArgumentException'在mscorlib.dll中
  4. 在Parse方法执行完毕之前,三个异常重复(尽管不一定按此顺序)。

    虽然我意识到自己并不需要自己处理这些异常,但我提到它们是因为我正在努力提高这种方法的性能并理解捕获异常可能是一项昂贵的操作。我正在寻找的是抛出这些异常的原因是什么,如果它依赖于我传入的错误数据,那么哪些数据会不好?

    这是目前的HTML到PDF功能。注意我已经尝试使用XMLWorkerFontProvider.DONTLOOKFORFONTS,正如itext_so手册所建议的那样,但这样做并没有带来任何性能提升。我还注意到NullReferenceExceptionPdfWriter.GetInstance抛出并被Parse吞噬了一次;我想知道这是否也与public static byte[] GeneratePdfFromHtml(string html, Action<PdfWriter, Document> pdfSettings = null, string additionalFooterText = null) { var tagProcessor = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory(); tagProcessor.RemoveProcessor(HTML.Tag.IMG); tagProcessor.AddProcessor(HTML.Tag.IMG, new CustomProcessorImageTag()); using (var workStream = new MemoryStream()) using (var document = new Document()) //NOTE: The NullReferenceException is thrown via this call. using (PdfWriter writer = PdfWriter.GetInstance(document, workStream)) { PdfEventHelper pdfEventHelper = new PdfEventHelper(additionalFooterText); writer.PageEvent = pdfEventHelper; writer.CloseStream = false; pdfSettings?.Invoke(writer, document); document.Open(); var xmlWorkerFontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS); //Not noticably faster without this font directory registration. xmlWorkerFontProvider.RegisterDirectory("~/Content/fonts", false); //TODO: If further performance is needed then this line is the next slowest (.43ms). var htmlContext = new HtmlPipelineContext(new CssAppliersImpl(xmlWorkerFontProvider)); htmlContext.SetTagFactory(tagProcessor); Func<string, string> mapPath = HttpContext.Current.Server.MapPath; var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); foreach (var cssFileName in new[] { "bootstrap.min.css", "Pdf.css", "Rdp.css" }) cssResolver.AddCssFile(mapPath($"~/Content/{cssFileName}"), true); using (var reader = new StringReader(html)) { new XMLParser( new XMLWorker( new CssResolverPipeline( cssResolver, new HtmlPipeline( htmlContext, new PdfWriterPipeline( document, writer))), true)) //TODO: Speed up this line - this is the slowest line in the method by far. //NOTE: This throws a series of ArgumentExceptions, NoDataExceptions and KeyNotFoundExceptions. .Parse(reader); document.Close(); return workStream.ToArray(); } } } 方法中抛出的异常有关。

    filter

0 个答案:

没有答案