peterjose

Posted 13-Dec-2020 | 128 | Javascript

How to align text in center using jspdf?

I am using jsPDF for my project where have to create a PDF from user submitted data. I want to align text in center for few inputs with jsPDF. According to the documentation I have tried using the following but no luck.

var doc = new jsPDF()
doc.text(10, 10, 'Invoice', { align: 'center' })
doc.save('file.pdf')

The final output i am getting is with text at left corner not at center. How to align the text with jsPDF?

Replies

icodefuture

Founder at Coders Diaries

Posted 15-Dec-2020

In order to set the text at the center, you can use the align attribute as the last parameter to the text method of jsPDF. According to the official documentation the following should work

var doc = new jsPDF()
doc.text('Hello JS', 20, 20, { align: 'center' })

However, I always got the output as the text was half cropped out of the PDF document to the very left. The only thing that worked for me is setting the x-axis value to 50% of the window inner width in combination with the align attribute.

var doc = new jsPDF()
var width = doc.internal.pageSize.getWidth()
doc.text('Centered text', width/2, 20, { align: 'center' })

The alternate option to do this could be the use of HTML. You can write HTML and convert that to PDF by using the html() method

2