PDFsharp & MigraDoc Forum

PDFsharp - A .NET library for processing PDF & MigraDoc - Creating documents on the fly
It is currently Sun Feb 01, 2026 3:19 pm

All times are UTC


Forum rules


Please read this before posting on this forum: Forum Rules

Also see our new Tailored Support & Services site.



Post new topic Reply to topic  [ 9 posts ] 
Author Message
PostPosted: Wed May 29, 2024 12:33 pm 
Offline

Joined: Wed May 29, 2024 12:20 pm
Posts: 3
When some rows in a table are merged down the height of the rows is not automatically increased to fit the text or image in the merged cell.

The issue occour in PDFsharp-MigraDoc-GDI Version="6.0.0"
It did work perfectly in PDFsharp-MigraDoc-GDI Version="1.50.5147"

I there any way to get around this?

Attachment:
Udklip.PNG
Udklip.PNG [ 27.45 KiB | Viewed 53963 times ]


Top
 Profile  
Reply with quote  
PostPosted: Wed May 29, 2024 1:00 pm 
Offline
PDFsharp Guru
User avatar

Joined: Sat Mar 14, 2015 10:15 am
Posts: 1067
Location: CCAA
This should still work.

See also:
https://docs.pdfsharp.net/General/Issue-Reporting.html

_________________
Best regards
Thomas
(Freelance Software Developer with several years of MigraDoc/PDFsharp experience)


Top
 Profile  
Reply with quote  
PostPosted: Wed May 29, 2024 3:25 pm 
Offline

Joined: Wed May 29, 2024 12:20 pm
Posts: 3
Here is some sample code

public void Test2()
{
Document document = new Document();
Section section = document.AddSection();

Table table = new Table();
table.Borders.Width = 0.75;

table.AddColumn("1cm");
table.AddColumn("2cm");
table.AddColumn("8cm");

Row row1 = table.AddRow();
table.AddRow();
table.AddRow();

table.Rows[0].Cells[2].MergeDown = 2;

row1.Cells[2].AddParagraph("slædkæl ækd la lsæakdlæas k dlskad lkslæd ksal dkaslkd lasækd laæs slædkasældk æsldlsakdælsakd laskdl ksa ldklaskdælaksld ksaæ saldk læsakdæl skdælskaldksaældkasældklæaskdl sald lsæakdlæas k dlskad lkslæd ksal dkaslkd lasækd laæs slædkasældk æsldlsakdælsakd laskdl ksa ldklaskdælaksld ksaæ saldk læsakdæl skdælskaldksaældkasældklæaskdl sald lsæakdlæas k dlskad lkslæd ksal dkaslkd lasækd laæs ldklaskdælaksld ksaæ saldk læsakdæl skdælskaldksaældkasældklæaskdl sald lsæakdlæas k dlskad lkslæd ksal dkaslkd lasækd laæs ");
document.LastSection.Add(table);

string folderName = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\";
string fileName = folderName + @"\pdfdocument2.pdf";

System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer();
pdfRenderer.Document = document;
pdfRenderer.RenderDocument();
pdfRenderer.PdfDocument.Save(fileName);
}


Top
 Profile  
Reply with quote  
PostPosted: Wed Jun 05, 2024 11:41 am 
Offline

Joined: Wed May 29, 2024 12:20 pm
Posts: 3
When some rows in a table are merged down the height of the rows is not automatically increased to fit the text or image in the merged cell.

The issue occour in PDFsharp-MigraDoc-GDI Version="6.0.0"
It did work perfectly in PDFsharp-MigraDoc-GDI Version="1.50.5147"

Attachment:
Udklip.PNG
Udklip.PNG [ 27.45 KiB | Viewed 53689 times ]


Here is some sample code

public void Test2()
{
Document document = new Document();
Section section = document.AddSection();

Table table = new Table();
table.Borders.Width = 0.75;

table.AddColumn("1cm");
table.AddColumn("2cm");
table.AddColumn("8cm");

Row row1 = table.AddRow();
table.AddRow();
table.AddRow();

table.Rows[0].Cells[2].MergeDown = 2;

row1.Cells[2].AddParagraph("slædkæl ækd la lsæakdlæas k dlskad lkslæd ksal dkaslkd lasækd laæs slædkasældk æsldlsakdælsakd laskdl ksa ldklaskdælaksld ksaæ saldk læsakdæl skdælskaldksaældkasældklæaskdl sald lsæakdlæas k dlskad lkslæd ksal dkaslkd lasækd laæs slædkasældk æsldlsakdælsakd laskdl ksa ldklaskdælaksld ksaæ saldk læsakdæl skdælskaldksaældkasældklæaskdl sald lsæakdlæas k dlskad lkslæd ksal dkaslkd lasækd laæs ldklaskdælaksld ksaæ saldk læsakdæl skdælskaldksaældkasældklæaskdl sald lsæakdlæas k dlskad lkslæd ksal dkaslkd lasækd laæs ");
document.LastSection.Add(table);

string folderName = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\";
string fileName = folderName + @"\pdfdocument2.pdf";

System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer();
pdfRenderer.Document = document;
pdfRenderer.RenderDocument();
pdfRenderer.PdfDocument.Save(fileName);
}


Top
 Profile  
Reply with quote  
PostPosted: Thu Jun 06, 2024 1:01 pm 
Offline
PDFsharp Guru
User avatar

Joined: Mon Oct 16, 2006 8:16 am
Posts: 3142
Location: Cologne, Germany
LeFroq wrote:
I there any way to get around this?
It is a bug. Thanks for the feedback.
Row height is correct with MergeDown = 1.
Problem occurs with MergeDown = 2 and MergeDown = 3. Most likely any value greater than 1 will show that bug.

If your requirements allow to work with MergeDown = 1, then the bug will not affect you.
I don't know when this bug will be fixed.
Sorry for the inconvenience.

_________________
Regards
Thomas Hoevel
PDFsharp Team


Top
 Profile  
Reply with quote  
PostPosted: Thu Feb 13, 2025 8:38 am 
Offline

Joined: Thu Feb 13, 2025 8:31 am
Posts: 1
I have exactly the same problem. Are there any news or a workaround?


Top
 Profile  
Reply with quote  
PostPosted: Mon Feb 17, 2025 9:59 am 
Offline
PDFsharp Guru
User avatar

Joined: Mon Oct 16, 2006 8:16 am
Posts: 3142
Location: Cologne, Germany
The bug was not fixed yet.

It may work if you add a zero-width dummy column to the table - no contents, no borders, no MergeDown on the dummy column.

_________________
Regards
Thomas Hoevel
PDFsharp Team


Top
 Profile  
Reply with quote  
PostPosted: Thu Jan 22, 2026 1:33 pm 
Offline

Joined: Thu Jan 22, 2026 1:23 pm
Posts: 1
Hi Thomas,
I just updated to 6.2.4 but the bug is still there.
I was not able to get any workaround solve my issue.
Tried Textframe and a zero sized dummy column.

Everything is working fine except this little but really annoying bug.

Any hint is welcome. Thank you.


Top
 Profile  
Reply with quote  
PostPosted: Sun Feb 01, 2026 12:27 pm 
Offline

Joined: Sun Feb 01, 2026 11:42 am
Posts: 1
VincentDontKnow wrote:
Any hint is welcome.

Hello.
You can use my helper class written for my project to fix this bug.
Code:
using System;
using System.Collections.Generic;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;

namespace YourProjectNamespace;

static class MigraDocHelper {
    /// <summary>
    /// Method for fixing the MergeDown bug.
    /// The method overrides the RowHeightRule of the last row, increasing the row height by the missing height value.
    /// </summary>
    /// <remarks>
    /// This fix internally clones the part of the table that contains the rows affected by the MergeDown.
    /// So, if there is a Cell inside this part of the table that has a MergeDown that continues further than this part of table, then an exception will be thrown.
    /// </remarks>
    /// <param name="pageAndStylesConfig">Configure the document according to how your page is configured and what styles are used in the document.</param>
    /// <param name="cell">Cell that has MergeDown</param>
    public static void MergedCellHeightFix(Action<Document> pageAndStylesConfig, Cell cell)
    {
        if (cell.Table == null || cell.Row == null)
            throw new Exception("Cell must be added to the table.");

        Table table = cell.Table;
        Row row = cell.Row;
        //Most likely bug occurs if MergeDown greater then 1
        if (cell.MergeDown > 1)
        {
            Table partiallyClonedTable = CreatePartiallyСlonedTable(table, row.Index, cell.MergeDown + 1);
            Unit partiallyClonedTableHeight = CalculateTablesHeight(pageAndStylesConfig, [partiallyClonedTable], BordersRenderOption.WithoutTopAndBottom);
            Unit cellHeight = CalculateCellHeight(pageAndStylesConfig, cell);
            if (cellHeight > partiallyClonedTableHeight)
            {
                Unit diffHeight = cellHeight - partiallyClonedTableHeight;

                Row lastRowOfMerge = table.Rows[row.Index + cell.MergeDown];
                Unit finalRowOfMergeHeight = CalculateRowHeight(pageAndStylesConfig, lastRowOfMerge);
                lastRowOfMerge.HeightRule = RowHeightRule.Exactly;
                lastRowOfMerge.Height = Unit.FromPoint(finalRowOfMergeHeight.Point + diffHeight.Point);
            }
        }
    }
    /// <summary>
    /// The method clones elements from Cell.Elements into the renderer to calculate the height.
    /// </summary>
    private static Unit CalculateCellHeight(Action<Document> pageAndStylesConfig, Cell cellFromInputTable)
    {
        Unit occupiedSpaceHeight = Unit.Zero;
        var document = new Document();
        var section = document.AddSection();
        pageAndStylesConfig(document);
        var table = new Table
        {
            Borders =
            {
                Width = 0
            },
        };
        Column? columnFromInputTable = cellFromInputTable.Column;
        if (columnFromInputTable == null) throw new Exception("Cell must be added to the table.");
        Column column = table.AddColumn();
        column.Width = columnFromInputTable.Width;
        column.Format = columnFromInputTable.Format.Clone();
        column.LeftPadding = columnFromInputTable.LeftPadding;
        column.RightPadding = columnFromInputTable.RightPadding;

        Row row = table.AddRow();
        Cell cell = row.Cells[0];
        foreach (var _element in cellFromInputTable.Elements)
        {
            switch (_element)
            {
                case MigraDoc.DocumentObjectModel.Paragraph _paragraph:
                    cell.Add(_paragraph.Clone());
                    break;
                case MigraDoc.DocumentObjectModel.Shapes.Image _image:
                    cell.Add(_image.Clone());
                    break;
                case MigraDoc.DocumentObjectModel.Shapes.Charts.Chart _chart:
                    cell.Add(_chart.Clone());
                    break;
                case MigraDoc.DocumentObjectModel.Shapes.TextFrame _textFrame:
                    cell.Add(_textFrame.Clone());
                    break;
                default:
                    throw new NotImplementedException();
            }
        }
        section.Add(table);

        Unit occupiedHeight = CalculateTablesHeightFromRender(document);
        return occupiedHeight;
    }

    public enum BordersRenderOption
    {
        All,
        WithoutTopAndBottom
    }
    private static Unit CalculateRowHeight(Action<Document> pageAndStylesConfig, Row row)
    {
        if (row.Table == null)
            throw new Exception("Row must be added to the table.");

        Table table = row.Table;
        Table partiallyClonedTable = CreatePartiallyСlonedTable(table, row.Index, 1);
        Unit partiallyClonedTableHeight = CalculateTablesHeight(pageAndStylesConfig, [partiallyClonedTable], BordersRenderOption.WithoutTopAndBottom);

        return partiallyClonedTableHeight;
    }
    public static Unit CalculateTablesHeight(Action<Document> pageAndStylesConfig, IEnumerable<Table> tables, BordersRenderOption bordersRenderOption)
    {
        var document = new Document();
        var section = document.AddSection();
        pageAndStylesConfig(document);

        foreach (var table in tables)
        {
            Table newTable = table.Clone();
            if (bordersRenderOption == BordersRenderOption.WithoutTopAndBottom)
            {
                newTable.Borders.Top.Clear();
                newTable.Borders.Bottom.Clear();
            }
            section.Add(newTable);
        }

        Unit occupiedHeight = CalculateTablesHeightFromRender(document);
        return occupiedHeight;
    }

    private static Unit CalculateTablesHeightFromRender(Document document)
    {
        Unit occupiedHeight = Unit.Zero;
        var renderer = new DocumentRenderer(document);
        renderer.PrepareDocument();
        DocumentObject[] documentobjects = renderer.GetDocumentObjectsFromPage(1);
        RenderInfo[]? info = renderer.GetRenderInfoFromPage(1);
        if (info == null) throw new NullReferenceException();
        for (int i = 0; i < documentobjects.Length; i++)
        {
            if (documentobjects[i] is Table)
            {
                var tableinfo = (MigraDoc.Rendering.TableRenderInfo)info[i];
                occupiedHeight += Unit.FromPoint(tableinfo.LayoutInfo.ContentArea.Height.Point);
            }
        }

        return occupiedHeight;
    }
    private static Table CreatePartiallyСlonedTable(Table inputTable, int startingRowIndex, int numberOfRowsToClone)
    {
        Table outputTable = new Table();
        outputTable.Columns = inputTable.Columns.Clone();
        if (numberOfRowsToClone < 0)
            throw new ArgumentOutOfRangeException("The number of rows to clone must be greater than 0.");
        if (startingRowIndex < 0)
            throw new ArgumentOutOfRangeException("The row index must not be negative.");
        int currentRowIndex = startingRowIndex;
        int remainingRowsNumber = numberOfRowsToClone;
        while (remainingRowsNumber > 0)
        {
            var row = outputTable.AddRow();
            row.Cells = inputTable.Rows[currentRowIndex].Cells.Clone();
            remainingRowsNumber --;
            currentRowIndex ++;
        }
        return outputTable;
    }
}


Here is an example of usage:

Code:
    // table creation code somewhere...
    row3.Cells[1].MergeDown = 3;

    // after all the table creation code
    Cell cellB3 = row3.Cells[1];
    MigraDocHelper.MergedCellHeightFix(document => PageAndStyleConfig(document), cellB3);

    // Your document must be configured with exactly the same config that you pass to the fix.
    private void PageAndStyleConfig(Document document)
    {
        var section = document.LastSection;
        var pageSetup = new PageSetup
        {
            PageFormat = PageFormat.A4,
            SectionStart = BreakType.BreakNextPage,
            Orientation = Orientation.Landscape,
            PageWidth = "29.7cm",
            PageHeight = "21cm",
            TopMargin = Unit.FromMillimeter(6),
            BottomMargin = Unit.FromMillimeter(6),
            LeftMargin = Unit.FromMillimeter(10),
            RightMargin = Unit.FromMillimeter(10),
            HeaderDistance = Unit.FromMillimeter(0),
            FooterDistance = Unit.FromMillimeter(0),
            OddAndEvenPagesHeaderFooter = false,
            DifferentFirstPageHeaderFooter = true,
            MirrorMargins = false,
            HorizontalPageBreak = false,
            StartingNumber = 1
        };
        section.PageSetup = pageSetup;

        var style = document.Styles[StyleNames.Normal]!;
        style.Font.Name = "Times New Roman";
        style.Font.Size = 10;

        style = document.Styles.AddStyle(MyCellStyle, StyleNames.Normal);
        style.Font.Name = "Times New Roman";
        style.Font.Size = 12;
        style.ParagraphFormat.Alignment = ParagraphAlignment.Center;
    }


I tested my fix on a table with only one affected cell. I can't guarantee that the fix will work with multiple affected cells. There's also a limitation: the cell we're fixing can't contain rows with other cells with MergeDown that extend beyond those rows.


Top
 Profile  
Reply with quote  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 9 posts ] 

All times are UTC


Who is online

Users browsing this forum: No registered users and 17 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
Privacy Policy, Data Protection Declaration, Impressum
Powered by phpBB® Forum Software © phpBB Group