Search code examples
c#pdfsharpmigradoc

C# PDFSharp and MigraDoc generating a table without wasting space


I recently started a project using PDF sharp + Migra Doc and I encounter a problem which I have seen in other posts, there is no fixing automatically. Table row will be generated on the next page if it doesn't have enough space and if there is still not enough space it will just go into the border and the text is lost. I am thinking of a workaround but I am not sure exactly how it can be done.

My think is as follows:

If I am able to check how many lines of text can fit in cell with the given string I can create a variable and increase it every time I add text. with the excess of text I can simply create a new row (which will be automatically be added on the next page) and thus fixing my problem. Even if I am not counting lines, is there a way to check if the row becomes too large for the current page? If at a given time I can check if the cell is too large and will be automatically sent to the next page I can trim the string up to the point it will fit, save the remaining words that didn't fit and maximise the space within the page.

this is how the document is generated currently

Is there a way to workaround this? That white space is useless and a waste of resources when it comes to a 30-40 pages document.


Solution

  • The solution that finally worked was as follows:

    • set up the style for the document including the header
    • depending on the data used create a for-loop which will input the desired rows in the table
    • top of the loop must add a row in the document
    • save in a variable how many pages the document currently contains(initially declare as 1 before entering the loop)
    • clone the document checking if the document you are passing contains the same number or more than the current document. If the document contains more pages means that the row you inputted exceeds the page. I was able to achieve this by rendering the document every time I was adding a new row.
    • an inner loop is necessary to trim the text within the row. The way I did it is split the text into sentences and if it contains more than 3 sentences trim, otherwise just let go to the next page.
    • make sure you always delete the last row on the inner loop otherwise you will end up with the same data

    It might not be the most efficient way but it renders 30+ pages documents in tables under 2 seconds on Azure servers. I hope this helps someone at some point.