【问题标题】:export html text to PDF (with inline styles). backgound-color does not work将 html 文本导出为 PDF(带有内联样式)。背景颜色不起作用
【发布时间】:2013-02-23 19:06:52
【问题描述】:

我正在开发一个将 html 数据导出到 pdf 文件(在 c# 中)的应用程序。我按照以下步骤转换数据

StyleSheet styles = new StyleSheet();
tempText = tempText.Replace("\"", """);
ArrayList objects = HTMLWorker.ParseToList(new StringReader(tempText), styles);
       for (int k = 0; k < objects.Count; k++)
       {
                document.Add((iTextSharp.text.IElement)objects[k]);
       }

假设我的文字是这样的

<h3 style="color:blue;">
       Write a Java 
       <span style="font-size:16px;">
           <span style="background-color:yellow;">
                program that prints two separate text
           </span> 
       </span>
       strings on the same line.

![ exported data in pdf is shown in the image below ][1]</h3>

问题是内部 span 标签的转换失败。它不会从样式中解析background-color。我怎样才能做到这一点?我不想使用任何第三方工具。

【问题讨论】:

    标签: c# pdf-generation html-to-pdf


    【解决方案1】:

    在 c#.Net Web 应用程序中将 Html 字符串导出为 pdf

    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=LetterListing.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter(PrintLetter());
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End();
    

    【讨论】:

    • 很好的答案,除了您省略了 using 语句并且 HTMLWorker 已过时。应该使用XMLWorkerHelper
    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多