iTextSharp: table row gets pushed to new page if it doesn't fit on the current one

11,230

Solution 1

The trick that worked for me is to inspect the results of ParseToList() and look for any elements that are of type PdfPTable. If you see one set its SplitLate property to False. Here's some VB that you should be able to convert to C# fairly easily:

Dim Elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(SR, Nothing)
For Each El In Elements
    If TypeOf El Is PdfPTable Then
        DirectCast(El, PdfPTable).SplitLate = False
    End If
    Doc.Add(El)
Next

Solution 2

Chris Haas answer is great - it worked for me. Here is one in C#:

        string template = File.ReadAllText(@"C:\my_template.html");
        var htmlText = Engine.Razor.RunCompile(template, Guid.NewGuid().ToString(), model: GetViewModel());

        TextReader reader = new StringReader(htmlText);
        var document = new Document(PageSize.A4, 30, 30, 30, 30);

        using (var stream = new MemoryStream())
        {
            PdfWriter.GetInstance(document, stream);

            document.Open();
            var pages = HTMLWorker.ParseToList(reader, new StyleSheet());
            foreach (var page in pages)
            {
                if (page is PdfPTable)
                {
                    (page as PdfPTable).SplitLate = false;
                }
                document.Add(page as IElement);
            }

            document.Close();

            File.WriteAllBytes(@"C:\my_template.pdf", stream.ToArray());
        }
Share:
11,230
Shagglez
Author by

Shagglez

Updated on June 04, 2022

Comments

  • Shagglez
    Shagglez almost 2 years

    I'm using iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(TextReader reader, StyleSheet style) to convert an html table into a pdf doc. Some rows contain a lot of data, and may not fit on the current page, so iTextSharp creates a new page and places the row there. If the row doesn't fit on the next page, it splits it correctly.

    Is there a way to tell it to not use these page breaks? Here is what it looks like:

    Row gets dropped to the next page by iTextSharp