Skip to content

Instantly share code, notes, and snippets.

Embed
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: https://gist.github.com/AnalyzePlatypus/55d806caa739ba6c2b27ede752fa3c9c
function addWrappedText({text, textWidth, doc, fontSize = 10, fontType = 'normal', lineSpacing = 7, xPosition = 10, initialYPosition = 10, pageWrapInitialYPosition = 10}) {
  doc.setFontType(fontType);
  doc.setFontSize(fontSize);
  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
      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
});  
@sainf
Copy link

sainf commented Feb 18, 2020

Hi.
You should move, "doc.setFontType" & "doc.setFontSize" to before "doc.splitTextToSize".
splitTextToSize uses current doc font specs to it's calcs.
http://raw.githack.com/MrRio/jsPDF/master/docs/src_modules_split_text_to_size.js.html

Thanks for warping in to a function.

@AnalyzePlatypus
Copy link
Author

AnalyzePlatypus commented Feb 18, 2020

Fixed.
Thanks for the heads up.

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