Sunday Ironfoot
Sunday Ironfoot

Reputation: 13050

iTextSharp - Outputting a segment of HTML into PDF (into a Table Cell)

I'm using iTextSharp to generate PDFs for an ASP.NET application, the PDF generation seems to work fine, though I'm finding iTextSharp a little unintuitive to use, but that's a different story.

I'm putting data into a table inside my PDF, now I want to place HTML content into a table cell and have it maintain the formatting/styling. I've seen plenty of examples show how to parse HTML into a PDF using iTextSharp and maintain formatting, but the examples all spit the content out directly into the document object eg. doc.addElement() I've tried to adapt the code to spit the parsed HTML content into a table cell eg. instead of...

objects = HTMLWorker.ParseToList(new StringReader(htmlString), styles);
for (int k = 0; k < objects.Count; ++k)
{
    document.Add((IElement) objects[k]);
}

I'm using...

Cell cell = new Cell();

objects = HTMLWorker.ParseToList(new StringReader(htmlString), styles);
for (int k = 0; k < objects.Count; ++k)
{
    cell.Add((IElement) objects[k]);
}

table.AddCell(cell);
document.Add(table);

However, it puts the data into the table cell all properly formatting, but with everything overlapping and on top of each other rather than spaced out. Is there anything I'm doing wrong.

The above code sample came from this website http://blog.rubypdf.com/2007/10/10/using-htmlworker-to-parse-html-snippets-and-convert-to-pdf/

Note: I'm not looking to maintain CSS styles, only that an <h1> roughly looks like what an <h1> normally looks like etc.

Upvotes: 5

Views: 12590

Answers (2)

denford mutseriwa
denford mutseriwa

Reputation: 538

for anyone looking for an updated answer since HTMLWorker is now absolute, see below:

var tableCell= new PdfPCell();
 string styles= "p { text-align: center; }"; 
 foreach (IElement element in XMLWorkerHelper.ParseToElementList(htmlString, styles))
    {
        tableCell.AddElement(element);
    }
table.AddCell(tableCell);
document.Add(table);

Upvotes: 1

manji
manji

Reputation: 47978

Use PdfPTable & PdfPCell classes instead of Table & Cell classes.
(I tried with Table/Cell, I got the same behavior you describe, but with PdfPtable/PdfPCell it was ok.)

Upvotes: 3

Related Questions