Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

itextsharp - Use External Css to parse XML

OK i am parsing HTML from a string into a PDFCEll.

It works great thanks to some help from here.

Here is how i am doing it.

How do i use an external css file so i can use class's and not STYLE=""

public class XhtmlToListHelper : IElementHandler
{
// Generic list of elements
public List<IElement> elements = new List<IElement>();
// Add the item to the list
public void Add(IWritable w)
{
  if (w is WritableElement)
  {
  elements.AddRange(((WritableElement)w).Elements());
  }
}

    string html = "<ul class="list"><li>html 1</li><li>html 2</li><li>html 3</li></ul>";
    using (TextReader sr = new StringReader(html))
    {
        XMLWorkerHelper.GetInstance().ParseXHtml(XhtmlHelper, sr);
    }
    foreach (var element in XhtmlHelper.elements)
    {
        if (element.IsContent())
        {
            PDFCell.AddElement(element);
        }
    }

Now i have got this far, but how to tye it all in evades me. Any help would be much apreacheted.

    HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
    htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory());
    ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
    cssResolver.AddCssFile(HttpContext.Current.Server.MapPath("~/Templates/css/core.css"), true);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you poke around the source here and you should see how to implement it. Basically, your three line using block quadruples in size and complexity:

var XhtmlHelper = new XhtmlToListHelper();
var htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory());
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(@"c:est.css", true);
var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new ElementHandlerPipeline(XhtmlHelper, null)));//Here's where we add our IElementHandler
var worker = new XMLWorker(pipeline, true);
var parser = new XMLParser();
parser.AddListener(worker);

using (TextReader sr = new StringReader(html)) {
    parser.Parse(sr);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...