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

11,995

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

Share:
11,995
Sunday Ironfoot
Author by

Sunday Ironfoot

ASP.NET MVC software developer. Just started getting to grips with NHibernate, Unit testing, SOLID, IOC containers etc.

Updated on June 04, 2022

Comments

  • Sunday Ironfoot
    Sunday Ironfoot about 2 years

    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.

  • Sunday Ironfoot
    Sunday Ironfoot over 14 years
    Awesome, that did the trick, thanks! For anyone else reading, just replace Table with PdfPTable and Cell with PDfPCell, it's that simple. BTW: careful not to confuse PdfPTable and PdfPCell with PdfTable and PdfCell, they're different types and won't work.
  • Armance
    Armance almost 13 years
    im using PDFPtable but i still see the tags like <p> instead of formatting the text as it should in html!!
  • rahularyansharma
    rahularyansharma about 3 years
    What if there is no css but my text contains something like this Basis Weight | lbs/1300 ft<sup>2</sup>