2013-03-15 58 views
2

出于某种原因,我似乎无法将样式应用于我的html元素。我为测试目的创建了一个样式包,但样式不适用于每个div元素。任何人都可以发现我做错了什么吗?iTextSharp中的HtmlTags在将html转换为pdf时不起作用

try 
{ 
    // set the file name 
    string file = "C:/MyPdf.pdf"; 

    // create a pdf document 
    Document document = new Document(); 

    // set the page size, set the orientation 
    document.SetPageSize(PageSize.A4); 

    // create a writer instance 
    PdfWriter pdfWriter = PdfWriter.GetInstance(document, new FileStream(file, FileMode.Create)); 

    // open the document 
    document.Open(); 

    // THIS STYLE IS SET FOR TESTING PURPOSES 
    StyleSheet styles = new StyleSheet(); 
    styles.LoadTagStyle(HtmlTags.DIV, HtmlTags.BGCOLOR, "#ff0000"); 

    // html pagina inlezen 
    string htmlText = File.ReadAllText("C:\\afl.html"); 

    // html pagina parsen in een arraylist van IElements 
    List<IElement> htmlElements = HTMLWorker.ParseToList(new StringReader(htmlText), styles); 

    // add the IElements to the document 
    for (int i = 0; i < htmlElements.Count; i++) 
    { 
     // cast the element 
     IElement htmlElement = ((IElement)htmlElements[i]); 
     document.Add(htmlElement); 
    } 

    // close the document 
    document.Close(); 

    // open the pdf document 
    //Process.Start(file); 
} 
catch (Exception ex) 
{ 
    var derp = ex.Message; 
} 

回答

2

HTMLWorker不再被主动维护,而是鼓励您使用XMLWorker。

也就是说,你会发现除了可能的基于表格的标签外,大多数标签都不支持背景颜色。这背后的原因是PDF规范本身不支持背景颜色。要实现这个iText需要使用复杂的注释或在文本后面绘制形状。

请参阅this link for the current XMLWorker documentation,单击左侧导航栏中的CSS支持以查看支持的各种属性。

你的代码本身是正确和有效的,它只是一个不支持的属性,不会引发任何错误。