0

My StringBuilder contains some HTML Code like a h1 element:

StringBuilder html = new StringBuilder();
html.Append("<h1 style='color:red;'>" + title + "</h1>");

Then i build a Table dynamically with different cell background-colors as a Table Object.

I need to append this table object to my StringBuilder to export the StringBuilder as PDF document with iTextSharp.

How can I append the Table to my StringBuilder and keep the background-colors of the cells?

This is the way how I generate the pdf document using iTextsharp:

bool isPrint = true; //tell the generate method that we will use this for print
generate gen = new generate(); //custom class that contains some functions
Object[] genObjects = new Object[2];
genObjects = gen.generateTable(currentTable._tableName, currentTable._tableID.ToString(), currentTable, isPrint);

//cast back to StringBuilder because object[] contains different types
StringBuilder sb = (StringBuilder)genObjects[1];
//Export HTML String as PDF.
StringReader sr = new StringReader(sb.ToString());
//need the pdf in landscape mode
Document pdfDoc = new Document(PageSize.A4.Rotate(), 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + friendlyName + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Hack4Life
  • 563
  • 1
  • 11
  • 34
  • What kind of `Table` class, ASP.NET? – Tim Schmelter Nov 19 '15 at 11:54
  • @TimSchmelter: `System.Web.UI.WebControls.Table` class – Hack4Life Nov 19 '15 at 11:55
  • So ASP.NET, how do you render the PDF with iTextSharp from a html-string? I see that [there are workarounds](http://stackoverflow.com/questions/2822843/itextsharp-html-to-pdf) but it seems not to be trivial. – Tim Schmelter Nov 19 '15 at 11:56
  • I have added the code for pdf generation. In [this article](http://www.aspsnippets.com/Articles/Generate-Invoice-Bill-Receipt-PDF-from-database-in-ASPNet-using-C-and-VBNet.aspx) it is also described with StringBuilder and HTML Code. – Hack4Life Nov 19 '15 at 12:06
  • 1
    You can use `RenderControl(table)` to get the HTML of the table. http://stackoverflow.com/questions/288409/how-do-i-get-the-html-output-of-a-usercontrol-in-net-c – Tim Schmelter Nov 19 '15 at 12:18
  • @TimSchmelter that works pretty well. But my background-colors of the cells are not rendered into the pdf document. do you know how I can resolve this? – Hack4Life Nov 19 '15 at 13:31

0 Answers0