Search code examples
htmlangular8html-to-pdfpage-breakpdfmake

htmlToPdf with PDFMake: How to add page break after every content in pdf (Angular 8)?


I am creating a pdf from an html string by html-to-pdfmake module and generating pdf by pdfmake.

Here is the code, there is convertToPDF func which will convert every html string in loop to pdf by the html-to-pdfmake module and then push it to another array i.e checkedArray, after that i had inserted the code to content of pdfmake and added a pagebreak, but its not working, it it merging all the content in one page, i want pages as per the content pushed in the pdfmake content,

so how i can do that?

import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
import htmlToPdf from 'html-to-pdfmake';

convertToPDF(resHtml) {
  for (var i = 0; i < resHtml.length; i++) {
    let data = resHtml[i].htmlString;
    let docId = resHtml[i].docId;
    let docTitle = resHtml[i].docTitle;
    var docDef = htmlToPdf(data);
    this.checkedArray.push({
      id: docId,
      title: docTitle,
      content: docDef
    });
  }
}

const docDefinition = {

  content: [],
  styles: {
    fontsize10: {
      fontSize: 10,
      bold: true
    },
    fontsize12: {
      fontSize: 12,
      bold: true
    },
    quote: {
      italics: true
    },
    small: {
      fontSize: 8
    },
    defaultStyle: {
      fontSize: 10
    },
    decoration: {
      decoration: 'underline'
    },
    tblHeader: {
      fontSize: 12,
      fillColor: '#1d86b8',
      color: '#ffffff',
      bold: true,
      overflow: 'ellipsize',
      tocItem: true,
    },
    subheader: {
      fontSize: 14,
      margin: [0, 10, 0, 5]
    },
  }
};

for (var i = 0; i < this.checkedArray.length; i++) {
  docDefinition.content.push(this.checkedArray[i].content);
  docDefinition.content.push({
    text: '',
    pagebreak: 'after'
  });
}

const pdfDocGenerator = pdfMake.createPdf(docDefinition);


Solution

  • You can add this function to your docDefinition

    <h1 class="pdf-pagebreak-before">My title on page 2</h1>
    
     pageBreakBefore: function(currentNode) {
        return currentNode.style && currentNode.style.indexOf('pdf-pagebreak-before') > -1;
      }