c# - 将 html 转换为 pdf 时,iTextSharp 中的 HtmlTags 不起作用

标签 c# pdf itext

出于某种原因,我似乎无法在我的 htmlElements 上应用样式。我创建了一个样式包用于测试目的,但该样式并未应用于每个 div 元素。有人能发现我做错了什么吗?

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;
}

最佳答案

不再积极维护 HTMLWorker,而是鼓励您使用 XMLWorker。

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

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

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

关于c# - 将 html 转换为 pdf 时,iTextSharp 中的 HtmlTags 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15438856/

相关文章:

java - 编译itext提供的示例程序

javascript - 使用 Python 将 HTML/CSS/Javascript 文件转换为 PDF?

c# - 将 PDF 中的外部链接转换为链接到 iTextSharp 中的嵌入式附件

c# - Autofac:使用 in 和 out 类型参数解析变体类型

c# - 将 Google 云端硬盘访问权限委托(delegate)给服务帐户失败

pdf - UIWebView内容高度在scrollview.contentsize中不正确

c# - 在 C# 中读取 PDF

pdf - 使用 iText 时某些 pdf 文件水印不显示

c# - 从 DuckDuckGo 下载 .ico 文件

c# - 无法通过 WCFTestClient 测试自托管 WCF 服务