Michiel van Vaardegem
Michiel van Vaardegem

Reputation: 2035

iTextSharp HTML to PDF doesn't render cell height correct after update

After an upgrade from iTextSharp 5.5.4.0 to 5.5.5.0 the rendering table cels from HTML to PDF isn't correct. The cells are way to high.

I didn't change anything in the code, the only thing I did was upgrading my DLL.

Is my code incorrect, or is this an error in the new version of iTextSharp.

My input files:

My output:

Below my code.

/// <summary>
/// Create a pdf based on a
/// </summary>
/// <param name="xHTMLContent"></param>
/// <param name="cssContent"></param>
/// <param name="outputStream"></param>
public static void CreateReportFromXHTML(string xHTMLContent, string cssContent, Rectangle pageSize, Stream outputStream)
{
    using (Document document = new Document(pageSize, 0f, 0f, 0f, 0f))
    {
        PdfWriter writer = PdfWriter.GetInstance(document, outputStream);
        document.Open();
        try
        {
            // CSS
            var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
            cssResolver.AddCss(cssContent, true);

            // HTML
            XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
            fontProvider.Register(System.Web.HttpContext.Current.Server.MapPath("~/Verdana.ttf"));
            fontProvider.Register(System.Web.HttpContext.Current.Server.MapPath("~/Verdana-Bold.ttf"));
            CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
            HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

            // Pipelines
            PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
            HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
            CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

            // XML Worker
            XMLWorker worker = new XMLWorker(css, true);
            XMLParser p = new XMLParser(worker);

            byte[] baContent = System.Text.Encoding.ASCII.GetBytes(xHTMLContent);

            using (MemoryStream msContent = new MemoryStream(baContent))
            {
                p.Parse(msContent);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Upvotes: 1

Views: 1308

Answers (1)

Chris Haas
Chris Haas

Reputation: 55417

The problem appears to actually be with your CSS:

td .group
{
    width: 140px; 
    font-weight: bold;
}

That literally is read as "any children of a td tag that has a class of group should have this rule". You, however, are using that class directly on the td tag so you should omit the space between the tag and the class selector. Making that simple change in my tests makes your table appear as you want it.

td.group
{
    width: 140px; 
    font-weight: bold;
}

Upvotes: 2

Related Questions