Search code examples
c#pdf-generationhtml-to-pdf

export html text to PDF (with inline styles). backgound-color does not work


I am developing an application to export html data to pdf file (in c#). I followed these steps to convert the data

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

lets suppose if my text is something like

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

The problem is that the conversion failed for the inner span tag. It does not parse background-color from style. How can I do this? I don't want to use any third party tool.


Solution

  • Exporting Html string to pdf in c#.Net web application

    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();