Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Helper function for line-wrapping in jsPDF

Line wrapping in jsPDF

jsPDF is a low-level library for building PDF files in JavaScript. It does not support multiline text.

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

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

// Assumes your document using is `pt` units
// If you're using any other unit (mm, px, etc.) use this gist to translate:
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, we'll use this for auto-paging. TRANSLATE this line if using units other than `pt`
  var cursorY = initialYPosition;

  textLines.forEach(lineText => {
    if (cursorY > pageHeight) { // Auto-paging
      cursorY = pageWrapInitialYPosition;
    doc.text(xPosition, cursorY, lineText);
    cursorY += lineSpacing;


// All values are jsPDF global units (default unit type is `px`)
const doc = new jsPDF();

  text: "'Twas brillig, and the slithy toves...", // Put a really long string here
  textWidth: 220,

  // 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
Copy link

sainf commented Feb 18, 2020

You should move, "doc.setFontType" & "doc.setFontSize" to before "doc.splitTextToSize".
splitTextToSize uses current doc font specs to it's calcs.

Thanks for warping in to a function.

Copy link

AnalyzePlatypus commented Feb 18, 2020

Thanks for the heads up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment