1

I'm trying to create a pdf that auto-pages when a content increases. This is my sample code. Any help would be greatly appreciated :)

HTML code

<div *ngFor="let data of data">
  <button click = "previewPdf(data)"> Preview </button>
</div>

Javascript

previewPdf(data) {
  var doc = new jsPDF();
  let bodyContent = doc.splitTextToSize(data.body, 250);
  let lineheight = 6;
  let offsety = 5;

  this.data.forEach(function(i) {
  doc.setFontSize(20);
  doc.text(10,10 + lineheight * 0 + offsety, bodyContent);
  doc.output("dataurlnewwindow");
});

}

JSON

data[{
  "body": "A very long letter content...";
}];

Edit: I have tried this sample code below and its giving me 2 pages and the last page is blank

previewPdf(data) {
    var doc = new jsPDF('p', 'mm', 'a4');
    let pageHeight = doc.internal.pageSize.getHeight();
    let bodyContent = doc.splitTextToSize(data.body, 250);
    let lineheight = 6;
    let offsetY = 5;


    doc.text(10, 10, bodyContent);
    // Before adding new content
    let y = 840; // Height position of new content
    if (y >= pageHeight) {
      doc.addPage();
      y = 0 // Restart height position
    }


    // this.data.forEach(function(i) {
    //   doc.setFontSize(20);
    //   
    // });
    doc.output("dataurlnewwindow");
  }

Julius
  • 53
  • 1
  • 9

2 Answers2

1

You can use addHTML for that using pagesplit parameter

Edit:

There's another dirty hack where you can calculate the height of the page remaining before adding content

doc = new jsPdf();

pageHeight= pdf.internal.pageSize.height; //get total page height

Then when adding content check height condition like below

pdf.text(x, y, "value");

if (y>=pageHeight)
{
pdf.addPage();
}
Alex
  • 878
  • 1
  • 10
  • 25
  • `var pdf = new jsPDF('p', 'pt', 'a4'); var options = { pagesplit: true }; pdf.addHTML($(".pdf-wrapper"), options, function() { pdf.save("test.pdf"); });` – Alex Apr 15 '19 at 09:21
1

Working solution

  previewPdf(data) {
    var doc = new jsPDF();

    var bodyContent = doc.splitTextToSize(data.body, 250);
    var pageHeight = doc.internal.pageSize.getHeight();
    doc.setFontType("normal");
    doc.setFontSize("12");

    var y = 15;
    for (var i = 0; i < bodyContent.length; i++) {
      if (y+10 > pageHeight) {
        y = 15;
        doc.addPage();
      }
      doc.text(10, y, bodyContent[i]);
      y = y + 7;
    }    
     doc.output('dataurlnewwindow');

  }

Julius
  • 53
  • 1
  • 9
  • above formula combined with the text wrap splitTextToSize(); based from here https://stackoverflow.com/a/43611535/8673882 – Julius Apr 16 '19 at 10:30