我使用以下代码在我的WPF应用程序中使用iTextSharp XMLWorker解析HTML字符串:
var css = "";
using (var htmlMS = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
{
//Create a stream to read our CSS
using (var cssMS = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(css)))
{
//Get an instance of the generic XMLWorker
var xmlWorker = XMLWorkerHelper.GetInstance();
//Parse our HTML using everything setup above
xmlWorker.ParseXHtml(writer, doc, htmlMS, cssMS, System.Text.Encoding.UTF8, fontProv);
}
}
解析工作正常但速度很慢,解析HTML大约需要2秒钟。因此,对于50页的pdf,大约需要2分钟。我在我的HTML字符串中使用内联样式。这是自然行为还是可以优化?
答案 0 :(得分:6)
这个问题是错误的,因为它表明HTML解析减慢了一切。这不是真的。甚至在解析第一段HTML片段之前就会出现瓶颈。
您正在使用最基本的一些代码行来自HTML创建PDF,如ParseHtml示例所示:
public void createPdf(String file) throws IOException, DocumentException {
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
document.open();
// step 4
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new FileInputStream(HTML));
// step 5
document.close();
}
此代码很简单,但它在内部执行了大量操作,如其他问题的评论中所述:XMLWorkerHelper performance slow。
注册字体目录的行为会耗费大量时间。您可以像ParseHtmlFonts示例中那样使用自己的FontProvider
来避免这种情况。
public void createPdf(String file) throws IOException, DocumentException {
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
writer.setInitialLeading(12.5f);
// step 3
document.open();
// step 4
// CSS
CSSResolver cssResolver = new StyleAttrCSSResolver();
CssFile cssFile = XMLWorkerHelper.getCSS(new FileInputStream(CSS));
cssResolver.addCss(cssFile);
// HTML
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.register("resources/fonts/Cardo-Regular.ttf");
fontProvider.register("resources/fonts/Cardo-Bold.ttf");
fontProvider.register("resources/fonts/Cardo-Italic.ttf");
fontProvider.addFontSubstitute("lowagie", "cardo");
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
// Pipelines
PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.parse(new FileInputStream(HTML));
// step 5
document.close();
}
在这种情况下,我们会指导iText DONTLOOKFORFONTS,从而节省大量时间。我们告诉iText我们将在HTML中使用哪些字体,而不是让iText查找字体。