Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to center text with jsPDF?

I'm trying to create a simple pdf doc using javascript. I found jsPDF but I don't figure out how to center text. Is it possible?

like image 861
Dev01 Avatar asked Jan 11 '14 09:01

Dev01


2 Answers

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); 
like image 133
Tsilis Avatar answered Sep 21 '22 03:09

Tsilis


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); } 
like image 26
sjy Avatar answered Sep 19 '22 03:09

sjy