2013-03-15 106 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支持以查看支持的各種屬性。

你的代碼本身是正確和有效的,它只是一個不支持的屬性,不會引發任何錯誤。