jspdf несогласованный перенос текста - PullRequest
0 голосов
/ 10 июля 2020
• 1000 . Последующий текст отображается правильно.

Вот пример кода и пример строки, которую он обрабатывает. В приведенном ниже примере первая строка в истории пользователя (если она была достаточно длинной) будет обернута примерно на 3/4 длины страницы.

См. Пример PDF здесь: https://www.dropbox.com/t/mKMz61a3mfbynDBN

var linebreak   = "<BR>";
var userstory   = "09/07/2020<BR>These are some words|10/07/2020<BR>These are some more words";
var rows        = userstory.split("|");
var xmargin     = 15;
var ymargin     = 25;
var ypos        = ymargin;
// new instance of jsPDF
var doc = new jsPDF({
    orientation: 'p',
    unit: 'mm',
    format: 'a4'
});
// max page content heights and widths
var pageHeight  = (doc.internal.pageSize.height - (ymargin * 2));
var pageWidth   = (doc.internal.pageSize.width - (xmargin * 2));
// set colour
// doc.setTextColor(100);
// split into array
doc.setFontSize(14);
doc.setFontType('bold');
doc.text("My Story", xmargin, ypos);
// populate with rows of data                   
rows.forEach(function(row, index){
    if(row !== "")
    {
        // set ypos
        ypos                    = (index === 0 ? ypos + 10 : ypos);
        var pieces              = row.split(linebreak);
        var date                = pieces[0];
        var content             = pieces[1];
        var splitcontent        = doc.splitTextToSize(content, pageWidth);
        var splitdate           = doc.splitTextToSize(date, pageWidth);
        var lineheightcontent   = doc.getLineHeight(content) / doc.internal.scaleFactor;
        var lineheightdate      = doc.getLineHeight(date) / doc.internal.scaleFactor;
        // do we need to start a new page?
        var totalheight         = ((lineheightdate * splitdate.length) + (lineheightcontent * splitcontent.length));
        // add new page, reset ypos?
        if(ypos + totalheight >= pageHeight)
        {
            doc.addPage();
            ypos = ymargin;
            doc.setFontSize(14);
            doc.setFontType('bold');
            doc.text("My Story", 15, ypos);
            ypos += 10;
        }
        doc.setFontSize(11);
        // write text
        doc.setFontType('bold');
        doc.text(splitdate, xmargin, ypos);
        // set font
        // write text
        doc.setFontType('normal');
        doc.text(splitcontent, xmargin, (ypos += 5));
        // new ypos
        ypos += (lineheightcontent * splitcontent.length);
        doc.text("", xmargin, (ypos += 10));
    }
});
doc.save("my-userstory.pdf");
...