Word wrap in generated PDF (using jsPDF)?

匿名 (未验证) 提交于 2019-12-03 01:59:02

问题:

what I'm doing is using jsPDF to create a PDF of the graph I generated. However, I am not sure how to wrap the title (added by using the text() function). The length of the title will vary from graph to graph. Currently, my titles are running off the page. Any help would be appreciated!

This is the code i have so far:

var doc = new jsPDF(); doc.setFontSize(18); doc.text(15, 15, reportTitle); doc.addImage(outputURL, 'JPEG', 15, 40, 180, 100); doc.save(reportTitle);

Nothing to keep the reportTitle from running off the page

回答1:

Okay I've solved this. I used the jsPDF function, splitTextToSize(text, maxlen, options). This function returns an array of strings. Fortunately, the jsPDF text() function, which is used to write to the document, accepts both strings and arrays of strings.

var splitTitle = doc.splitTextToSize(reportTitle, 180); doc.text(15, 20, splitTitle);


回答2:

If you need to dynamically add new lines you want to access the array returned by doc.splitTextToSize and then add more vertical space as you go through each line:

var y = 0, lengthOfPage = 500, text = [a bunch of text elements];  //looping thru each text item for(var i = 0, textlength = text.length ; i < textlength ; i++) {      var splitTitle = doc.splitTextToSize(text[i], lengthOfPage);      //loop thru each line and output while increasing the vertical space     for(var c = 0, stlength = splitTitle.length ; c < stlength ; c++){          doc.text(y, 20, splitTitle[c]);         y = y + 10;      }  }


回答3:

When we use linebreak in jsPDF we get an error stating b.match is not defined, to solve this error just unminify the js and replace b.match with String(b).match and u will get this error twice just replace both and then we get c.split is not defined just do the same in this case replace it with String(c).match and we are done. Now you can see line breaks in you pdf. Thank you



回答4:

Auto-paging and text wrap issue in JSPDF can achieve with following code

 var splitTitle = doc.splitTextToSize($('#textarea').val(), 270);     var pageHeight = doc.internal.pageSize.height;     doc.setFontType("normal");     doc.setFontSize("11");     var y = 7;     for (var i = 0; i < splitTitle.length; i++) {                         if (y > 280) {             y = 10;             doc.addPage();         }         doc.text(15, y, splitTitle[i]);         y = y + 7;     }     doc.save('my.pdf');


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!