Search code examples
javascriptpdfpdfmake

Dynamic check if text Goes to next page and add pagebreak in pdf using pdfmake


For a project im making offer and invoice pdf's on the fly using pdfmake in javascript. The problem im facing is having text blocks going off the page in the middle. What i want is to check if a certain block of text or a table is going to be split between pages and if so add a pagebreak before the block to make sure the text or table will be entirely on one page.

My pdf docDefinition is build like this:

return {
                content: [
                    getOfferLogo(), //Get the logo or empty string
                    getHeading(), //get the customer and business data (adress etc)
                    //the above is always the same
                    getText(), //get the textblock, created by user and always different
                    getSpecifics(), //get a table of payment specifications
                    getSignature() //get last textblock contaning signature fields etc, always the same
                ],
                styles: {
                    subheader: {
                        fontSize: 15,
                        bold: true,
                        alignment: 'center'
                    }
                },
                defaultStyle: {
                    columnGap: 20,
                    fontSize: 12
                }
            };

So in short how can i check if text will be going off the page before creating the pdf and add pagebreaks accordingly?

Thanks in advance.


Solution

  • Found the solution :)

    In the DocDefinition you can add a function for pageBreakBefore like this:

    content: [{
        text: getOfferClosingParagraph(),
        id: 'closingParagraph'
      }, {
        text: getSignature(),
        id: 'signature'
      }],
      pageBreakBefore: function(currentNode, followingNodesOnPage, nodesOnNextPage, previousNodesOnPage) {
        //check if signature part is completely on the last page, add pagebreak if not
        if (currentNode.id === 'signature' && (currentNode.pageNumbers.length != 1 || currentNode.pageNumbers[0] != currentNode.pages)) {
          return true;
        }
        //check if last paragraph is entirely on a single page, add pagebreak if not
        else if (currentNode.id === 'closingParagraph' && currentNode.pageNumbers.length != 1) {
          return true;
        }
        return false;
      },

    For more info about this function and the information provided take a look at this