Is there any way to center text with jsPDF?

前端 未结 9 1211
半阙折子戏
半阙折子戏 2021-02-01 02:07

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?

9条回答
  •  旧巷少年郎
    2021-02-01 02:53

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

提交回复
热议问题