Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align text in center using jspdf

Tags:

jspdf

How to align text center using jsPDF.

var doc = new jsPDF();
doc.text(40, 250, 'Hi How are you');
like image 892
Mickey Patel Avatar asked Jan 28 '16 13:01

Mickey Patel


5 Answers

Above answers didn't work for me, I ended up doing the following to center the text

let textX = (doc.internal.pageSize.getWidth() - doc.getTextWidth(text))/2
doc.text(text, textX, textY);
like image 178
stor314 Avatar answered Oct 17 '22 15:10

stor314


If you are using the latest version (1.1.135) the api has changed some for the text function. It now reads as:

API.text = function(text, x, y, flags, angle, align);

If you don't need to use the flags or angle though, you can simply use:

var doc = new jsPDF();
doc.text('Hi How are you', 40, 250, 'center');

Keep in mind that the center call uses the x parameter now as the center of the text string, and not the left most border as it does when rendering left aligned.

Link to source

Edit:

Alternately you can calculate the proper x offset to just use the text function normally like so:

var text = "Hi How are you",
    xOffset = (doc.internal.pageSize.width / 2) - (doc.getStringUnitWidth(text) * doc.internal.getFontSize() / 2); 
doc.text(text, xOffset, 250);
like image 38
GrouchyPanda Avatar answered Oct 17 '22 14:10

GrouchyPanda


Angular 6. Footer align to horizontally center

var doc = new jsPDF();
var pageHeight = doc.internal.pageSize.height || doc.internal.pageSize.getHeight();
var pageWidth = doc.internal.pageSize.width || doc.internal.pageSize.getWidth();


// FOOTER
let str = "Your footer text";
doc.setTextColor(100);
doc.setFontSize(10);
doc.text(str, pageWidth / 2, pageHeight  - 10, {align: 'center'});
doc.save("example.pdf");
like image 16
Włodzimierz Woźniak Avatar answered Oct 17 '22 14:10

Włodzimierz Woźniak


this worked:

var xOffset = doc.internal.pageSize.width / 2
        doc.text('hello world', xOffset, 8, {align: 'center'});
like image 2
Mohammad Nadr Avatar answered Oct 17 '22 15:10

Mohammad Nadr


2022: this works assuming your page width is 210 (default A4).

doc.text("This is centred text.", 105, 80, null, null, "center");

Here's a link to their live demo per the README:

http://raw.githack.com/MrRio/jsPDF/master/index.html

like image 1
makisupa488 Avatar answered Oct 17 '22 16:10

makisupa488