Is there any way to center text with jsPDF?

I have found that the current version of jsPdf supports a parameter 'align' with the function signature like this:

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

So the following should give you a center-aligned text:

doc.text('The text', doc.internal.pageSize.width, 50, null, null, 'center');

However, at the current point in time, an error is thrown in the library when strict mode is on because a 'var' is missing. There is an issue and pull request for it, but the fix hasn't made it in: https://github.com/MrRio/jsPDF/issues/575

Whoever is looking for this, one day, you might be able to use this to make it easier to center text.


Yes it's possible. You could write a jsPDF plugin method to use.

One quick example is this:

    (function(API){
    API.myText = function(txt, options, x, y) {
        options = options ||{};
        /* Use the options align property to specify desired text alignment
         * Param x will be ignored if desired text alignment is 'center'.
         * Usage of options can easily extend the function to apply different text 
         * styles and sizes 
        */
        if( options.align == "center" ){
            // Get current font size
            var fontSize = this.internal.getFontSize();

            // Get page width
            var pageWidth = this.internal.pageSize.width;

            // Get the actual text's width
            /* You multiply the unit width of your string by your font size and divide
             * by the internal scale factor. The division is necessary
             * for the case where you use units other than 'pt' in the constructor
             * of jsPDF.
            */
            txtWidth = this.getStringUnitWidth(txt)*fontSize/this.internal.scaleFactor;

            // Calculate text's x coordinate
            x = ( pageWidth - txtWidth ) / 2;
        }

        // Draw text at x,y
        this.text(txt,x,y);
    }
})(jsPDF.API);

And you use it like this

var doc = new jsPDF('p','in');
doc.text("Left aligned text",0.5,0.5);
doc.myText("Centered text",{align: "center"},0,1);

This works in the scratchpad on the jsPdf homepage:

var centeredText = function(text, y) {
    var textWidth = doc.getStringUnitWidth(text) * doc.internal.getFontSize() / doc.internal.scaleFactor;
    var textOffset = (doc.internal.pageSize.width - textWidth) / 2;
    doc.text(textOffset, y, text);
}