How to align text in center using jspdf

Mickey Patel picture Mickey Patel · Jan 28, 2016 · Viewed 35k times · Source

How to align text center using jsPDF.

var doc = new jsPDF();
doc.text(40, 250, 'Hi How are you');

Answer

GrouchyPanda picture GrouchyPanda · Feb 26, 2016

If you are using the latest version (1.1.135) the api has changed some for the text function. It now reads as:

API.text = function(text, x, y, flags, angle, align);

If you don't need to use the flags or angle though, you can simply use:

var doc = new jsPDF();
doc.text('Hi How are you', 40, 250, 'center');

Keep in mind that the center call uses the x parameter now as the center of the text string, and not the left most border as it does when rendering left aligned.

Link to source

Edit:

Alternately you can calculate the proper x offset to just use the text function normally like so:

var text = "Hi How are you",
    xOffset = (doc.internal.pageSize.width / 2) - (doc.getStringUnitWidth(text) * doc.internal.getFontSize() / 2); 
doc.text(text, xOffset, 250);