levi
levi

Reputation: 1147

Prevent text splitting to two pages in jsPDF

I using the jsPDF and html2canvas packages to save a PDF file from HTML.

My problem is that the content is dynamic, and i don't know when each page ended.

I use this function to create the PDF and split the content to pages.

But some time text line can break to two pages. How can I prevent this?

 import { Injectable } from '@angular/core';
 import jsPDF from 'jspdf';
 import html2canvas from 'html2canvas';

createpdf() {
var data = document.getElementById('parentdiv');
var date = new Date();
html2canvas(data).then(canvas => {
  var imgWidth = 210;
  var pageHeight = 295;
  var imgHeight = canvas.height * imgWidth / canvas.width;
  var heightLeft = imgHeight;

  //enter code here
  const imgData = canvas.toDataURL('image/png')

  var doc = new jsPDF('p', 'mm');
  console.log(doc)
  var position = 0;

  doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight + 15);
  heightLeft -= pageHeight;

  while (heightLeft >= 0) {
    position = heightLeft - imgHeight;
    doc.addPage();
    doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight + 15);
    heightLeft -= pageHeight;
  }
  doc.save('Visiometria_' + date.getTime() + '.pdf')

});
}

Upvotes: 4

Views: 2503

Answers (1)

akshay
akshay

Reputation: 1161

You can prevent this by setting the PDF page Height exact same to the image height. You can even set different sizes for every page

var doc = new jsPDF('p', 'mm', [68,20]);
doc.addPage(100, 200);

for single page you can try below code

createpdf() {
    var data = document.getElementById('parentdiv');
    var date = new Date();
    html2canvas(data).then(canvas => {
        var imgWidth = 210;
        var pageHeight = 295;
        var imgHeight = canvas.height * imgWidth / canvas.width;
        var heightLeft = imgHeight;

        //enter code here
        const imgData = canvas.toDataURL('image/png')
        if("portrait"){
            var doc = new jsPDF('p', 'mm', [210, imgHeight]);
        } else {
            var doc = new jsPDF('l', 'mm', [297, imgHeight]);
        }

        var position = 0;

        doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        doc.save('Visiometria_' + date.getTime() + '.pdf')

    });
}

Upvotes: 1

Related Questions