37

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?

sjy
  • 2,512
  • 1
  • 18
  • 22
Dev01
  • 10,909
  • 17
  • 64
  • 109

9 Answers9

65

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);
Jeffrey Nicholson Carré
  • 2,511
  • 1
  • 22
  • 38
Tsilis
  • 716
  • 5
  • 3
  • 1
    I also was able to create an align right using this code `x = (typeof x != "undefined" ? (( pageWidth - txtWidth ) - x) : ( pageWidth - txtWidth ) );` – Hunter WebDev Jul 16 '14 at 17:38
  • 1
    @MrHunter can you show me the full code for right alignment text – Ashok Shah Aug 11 '14 at 12:17
  • 1
    @AshokShah It's the exact same code as above except replace the `x = ( pageWidth - txtWidth ) / 2;` with the code I provided. – Hunter WebDev Aug 11 '14 at 13:17
  • Thanks a lot for the approach but that equation won't always work if txtWidth is similar to pageWidth. The correct equation is x = pageWidth - (txtWidth / 2), where by the way you can replace pageWidth with any given x offset. – Enzo Ferey Feb 24 '18 at 23:15
37

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);
}
BenRoe
  • 975
  • 10
  • 22
sjy
  • 2,512
  • 1
  • 18
  • 22
12

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.

Ben
  • 1,309
  • 16
  • 20
  • 12
    Although this answer did not work as described with the current release version of `jspdf` it did point me in the right direction. The only difference being the need to use `doc.internal.pageSize.getWidth() / 2` instead of `doc.internal.pageSize.width`. – Jake Holzinger Aug 30 '18 at 20:23
  • the comments solution works very well – Moxet Jan Jan 04 '21 at 17:04
  • the comment by @JakeHolzinger did work for me. I USED doc.internal.pageSize.getWidth() + {align: 'center'} and it works just fine – hamza saber Mar 16 '21 at 11:56
8

WootWoot, just in case you need more layout options, you could also take a look at my pdfmake library

It supports:

  • text alignments, lists, margins
  • styling (with style inheritance)
  • tables with auto/fixed/star sized columns, auto-repeated headers, col/row spans
  • page headers and footers
  • font embedding, and a couple of other options

It works on client-side (pure JS) or server-side (an npm module)

Take a look at the playground to see what's possible

Good luck

bartekp
  • 551
  • 5
  • 6
4

I had the same problem and a lot of others while creating PDF-Files (e.g. auto-pagebreak, total-pageCount). So i started writing a little lib, which depends on jsPDF but gives you a lot of features in a way you know them (form HTML/CSS and jQuery). You can find it on GitHub. I hope it makes PDF-Creating easier... =)

platdesign
  • 84
  • 3
  • Thanks! Looks great! I had to put the PDF portion of my project aside and I'm just getting back to it now. I just glanced at your example http://jsfiddle.net/GE6QV/6/ and it looks really easy to use. Thanks! – Dev01 May 09 '14 at 06:45
  • Thank you. =) It is really in the early stages but it'll get more functionality, cause i need it myself ;) Let me know if you have questions or suggestions on it. :) – platdesign May 13 '14 at 04:43
3

Based on @Tsilis answer I have snippet out a plugin here https://gist.github.com/Purush0th/7fe8665bbb04482a0d80 which can align the text left, right and center in the given text container width.

(function (api, $) {
'use strict';
api.writeText = function (x, y, text, options) {
    options = options || {};

    var defaults = {
        align: 'left',
        width: this.internal.pageSize.width
    }

    var settings = $.extend({}, defaults, options);

    // Get current font size
    var fontSize = this.internal.getFontSize();

    // 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.
    */
    var txtWidth = this.getStringUnitWidth(text) * fontSize / this.internal.scaleFactor;

    if (settings.align === 'center')
        x += (settings.width - txtWidth) / 2;
    else if (settings.align === 'right')
        x += (settings.width - txtWidth);

    //default is 'left' alignment
    this.text(text, x, y);

}
})(jsPDF.API, jQuery);

Usage

var doc = new jsPDF('p', 'pt', 'a4');
//Alignment based on page width
doc.writeText(0, 40 ,'align - center ', { align: 'center' });
doc.writeText(0, 80 ,'align - right ', { align: 'right' });
//Alignment based on text container width
doc.writeText(0, 120 ,'align - center : inside container',{align:'center',width:100});
Purushoth
  • 2,185
  • 1
  • 20
  • 35
2

doc.text(text,left,top,'center') can be used to center text. It can be used with array of lines as well but when it is used with array the center does not work right so I have used it in a loop for every object in the array.

var lMargin=15; //left margin in mm
var rMargin=15; //right margin in mm
var pdfInMM=210;  // width of A4 in mm
var pageCenter=pdfInMM/2;

var doc = new jsPDF("p","mm","a4");
var paragraph="Apple's iPhone 7 is officially upon us. After a week of pre-orders, the latest in the iPhone lineup officially launches today.\n\nEager Apple fans will be lining up out the door at Apple and carrier stores around the country to grab up the iPhone 7 and iPhone 7 Plus, while Android owners look on bemusedly.\n\nDuring the Apple Event last week, the tech giant revealed a number of big, positive changes coming to the iPhone 7. It's thinner. The camera is better. And, perhaps best of all, the iPhone 7 is finally water resistant.\n\nStill, while there may be plenty to like about the new iPhone, there's plenty more that's left us disappointed. Enough, at least, to make smartphone shoppers consider waiting until 2017, when Apple is reportedly going to let loose on all cylinders with an all-glass chassis design.";

var lines =doc.splitTextToSize(paragraph, (pdfInMM-lMargin-rMargin));
var dim = doc.getTextDimensions('Text');
var lineHeight = dim.h
for(var i=0;i<lines.length;i++){
  lineTop = (lineHeight/2)*i
  doc.text(lines[i],pageCenter,20+lineTop,'center'); //see this line
}
doc.save('Generated.pdf');
Saifee
  • 899
  • 1
  • 12
  • 27
1

maybe... just for easy way, you may read this jsPdf text api doc

doc.text(text, x, y, optionsopt, transform) 

where optionspot is a objet, so you can do this

{align:"center"}

i.e:

doc.text("Hello Sun", doc.internal.pageSize.getWidth()/2, 10, { align: "center" })

where: doc.internal.pageSize.getWidth() is the page width for pdf sheet

Edgar Olivar
  • 490
  • 6
  • 6
  • isn't the center made by `doc.internal.pageSize.getWidth()/2` ? Why use `{ align: "center" }` ? – Boris BELLOC Mar 24 '20 at 01:11
  • 1
    @BorisBELLOC I think the text will start from the center of the width to the right. in this case the text is still not centered. It only start from center and move towards right. – Santosh Jan 08 '21 at 07:59
1

Do this:

First get the page width, get half the page width and use it as the x value, use y value of your choice and pass center as the third param to center your text. Read more from documentation

let doc = new jsPDF();
let pageWidth = doc.internal.pageSize.getWidth();
doc.text("My centered text",pageWidth / 2, 20, 'center');
7guyo
  • 1,358
  • 13
  • 23