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?
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With