Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word wrap in generated PDF (using jsPDF)?

Tags:

jspdf

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

like image 218
user3749946 Avatar asked Jun 17 '14 19:06

user3749946


4 Answers

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);
like image 57
user3749946 Avatar answered Nov 16 '22 12:11

user3749946


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');
like image 11
KB1788 Avatar answered Nov 16 '22 12:11

KB1788


You can just use the optional argument maxWidth from the text function.

doc.text(15, 15, reportTitle, { maxWidth: 40 });

That will split the text once it reaches the maxWidth and start on the next line.

like image 9
Paul Avatar answered Nov 16 '22 11:11

Paul


To wrap long string of text to page use this code:

var line = 25 // Line height to start text at
var lineHeight = 5
var leftMargin = 20
var wrapWidth = 180
var longString = 'Long text string goes here'

var splitText = doc.splitTextToSize(longString, wrapWidth)
for (var i = 0, length = splitText.length; i < length; i++) {
  // loop thru each line and increase
  doc.text(splitText[i], leftMargin, line)
  line = lineHeight + line
}
like image 5
gaskills Avatar answered Nov 16 '22 11:11

gaskills