Word wrap in generated PDF (using jsPDF)?

后端 未结 6 2029
梦毁少年i
梦毁少年i 2020-12-01 06:06

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

6条回答
  •  执笔经年
    2020-12-01 06:41

    Working Helper function

    Here's a complete helper function based on the answers by @KB1788 and @user3749946:

    It includes line wrap, page wrap, and some styling control:

    (Gist available here)

    function addWrappedText({text, textWidth, doc, fontSize = 10, fontType = 'normal', lineSpacing = 7, xPosition = 10, initialYPosition = 10, pageWrapInitialYPosition = 10}) {
      var textLines = doc.splitTextToSize(text, textWidth); // Split the text into lines
      var pageHeight = doc.internal.pageSize.height;        // Get page height, well use this for auto-paging
      doc.setFontType(fontType);
      doc.setFontSize(fontSize);
    
      var cursorY = initialYPosition;
    
      textLines.forEach(lineText => {
        if (cursorY > pageHeight) { // Auto-paging
          doc.addPage();
          cursorY = pageWrapInitialYPosition;
        }
        doc.text(xPosition, cursorY, lineText);
        cursorY += lineSpacing;
      })
    }
    

    Usage

    // All values are jsPDF global units (default unit type is `px`)
    const doc = new jsPDF();
    
    addWrappedText({
      text: "'Twas brillig, and the slithy toves...", // Put a really long string here
      textWidth: 220,
      doc,
    
      // Optional
      fontSize: '12',
      fontType: 'normal',
      lineSpacing: 7,               // Space between lines
      xPosition: 10,                // Text offset from left of document
      initialYPosition: 30,         // Initial offset from top of document; set based on prior objects in document
      pageWrapInitialYPosition: 10  // Initial offset from top of document when page-wrapping
    });  
    

提交回复
热议问题