Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
15
rated 0 times [  18] [ 3]  / answers: 1 / hits: 64633  / 11 Years ago, sat, january 11, 2014, 12:00:00

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?


More From » jspdf

 Answers
5

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);

[#73245] Friday, January 10, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stephonkeandrer

Total Points: 392
Total Questions: 94
Total Answers: 100

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
;