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 itemfor(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 spacefor(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');