简体   繁体   中英

How to add margin after using page-break-modes with html2pdf.js?

Converting html to pdf using html2pdf. I need to add margin-top and margin-bottom after pagebreak elements.

This is a page-break-modes

FIDDLE example

var element = document.getElementById('element-to-print');


 var opt = {
            margin: [0, 0, 30, 0], //top, left, buttom, right,
            filename: 'my_file.pdf',
            image: {type: 'jpeg',quality: 0.98},
            html2canvas: {dpi: 192, scale: 2, letterRendering: true},
            pagebreak: {mode: 'avoid-all'},
            jsPDF: {unit: 'pt', format: 'a4', orientation: 'portrait'}
        };
        var worker = html2pdf();

            console.log(worker);
            worker.set(opt)
                  .from(element)
                  .toPdf()
                  .get('pdf')
                  .then(function (doc) {
                      var totalPages = doc.internal.getNumberOfPages();
                      for (var i=1; i<=totalPages; i++) {
                          if (i > 1) {
                            doc.setPage(i);
                            //?????
                          }
                      }

                 }).save();  

This is a similar case .

Here, I have split the content to render in two pdf pages using proper page break and also set the margin-top for each page.

<button id="btnTest">Generate PDF</button>
  <div id ="root">

  <div>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
  </div>
 <div id="nextpage1">
    Lorem Ipsum is simply dummied text of the printing and typesetting industry. 
 </div>

div {
   outline: red solid 1px;
   page-break-inside: avoid;
}
#nextpage1 {
  page-break-before: always;
}

 html2pdf().from(element).set({
   margin:       [1, 0, 0, 0], 
   filename: 'samplepdf.pdf',
   pageBreak: { mode: 'css', before:'#nextpage1'},
   jsPDF: {orientation: 'landscape', unit: 'in', format: 'letter'}
}).toPdf().get('pdf').then(function (pdf) {
   var totalPages = pdf.internal.getNumberOfPages();
   for (i = 1; i <= totalPages; i++) {
     pdf.setPage(i);
     pdf.setFontSize(10);
     pdf.setTextColor(150);
     pdf.text('This is the header text', (pdf.internal.pageSize.getWidth()/2.40), (pdf.internal.pageSize.getHeight()-8));      
     pdf.text('Page ' + i + ' of ' + totalPages, pdf.internal.pageSize.getWidth()/2.25), (pdf.internal.pageSize.getHeight() - 1));
  }}).save();

Try out this and please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM