Skip to content

Instantly share code, notes, and snippets.

@sainf
Forked from AnalyzePlatypus/jsPDF_line_wrap.md
Last active April 27, 2024 05:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sainf/d02963d45a7107c2168c93131ac43b0c to your computer and use it in GitHub Desktop.
Save sainf/d02963d45a7107c2168c93131ac43b0c to your computer and use it in GitHub Desktop.
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. It does, text accept array, just split with splitTextToSize

Based on: https://gist.github.com/AnalyzePlatypus/c54d520e9bd5b5f662aeb0276e3f01a4

It includes line wrap WITH page wrap:

/**
 * Multiline page break
 * It includes line wrap, page wrap:
 *
 * Based on: https://gist.github.com/AnalyzePlatypus/c54d520e9bd5b5f662aeb0276e3f01a4
 *
 * TODO: add text align and fix justify with custom fonts
 *
 * @param {Object} doc The jsDoc Object
 * @param {string} text The long text string
 * @param {Number} [xPosition=15] Text offset from left of document
 * @param {Number} [initialYPosition=30] Initial offset from top of document; set based on prior objects in document
 * @param {Number} [finalYPosition=280] Final offset from top of document; set based on prior objects in document
 * @param {Number} [lineSpacing=1.5] Space between lines
 * @param {Number} [textWidth=doc.internal.pageSize.width - xPosition * 2] Max text width
 * @param {Number} [pageWrapInitialYPosition=20] Initial offset from top of document when page-wrapping
 * @returns {Number} The last next line position
 */
export function addWrappedText(
  doc,
  text,
  xPosition = 15,
  initialYPosition = 30,
  finalYPosition = 280,
  lineSpacing = 1.5,
  textWidth,
  pageWrapInitialYPosition = 20
) {
  const maxTextWidth = doc.internal.pageSize.width - xPosition * 2
  let cursorY = initialYPosition

  const textLines = doc.splitTextToSize(text, textWidth || maxTextWidth)

  textLines.forEach(lineText => {
    if (cursorY > finalYPosition) {
      // Auto-paging
      doc.addPage()
      cursorY = pageWrapInitialYPosition
    }
    doc.text(lineText, xPosition, cursorY)
    cursorY += 0.3527 * doc.getFontSize() * lineSpacing
  })

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