How to Justify text in pdf using jsPDF!

jsPDF is a client side Javascript PDF generator. This makes it very easy to export a web page on the fly or on an event (like on button click). To learn more about how to use jsPDF check the simple solution.

There have been challenges and bugs raised in jsPDF related to justify text in jsPDF. Going through all the bugs, comments looking for a solution is cumbersome. In this example we will show how to justify text in jsPDF. We have created an html page which can be exported to pdf on ‘Export to PDF’ button click. JSFiddle is also available

     <script src="" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/" crossorigin="anonymous"></script>
<div id="banner-message">
<div id="demo">This is a demo text. The text will be justified in the exported pdf using jsPDF. The solution is to provide a maximum Widget to the text using the maxWidth  property and then align as 'Justify'.</div>
<div>Click on the button below to export me</div>
<button>Export to PDF</button></div>

The html looks as shown below:

jsPDF justify
The webpage with Export to PDF button.

Create a JavaScript function to write the jsPDF logic.

button.on("click", function(){
     var doc = new jsPDF()
     doc.setTextColor(0, 0, 255);
     doc.text(demo, 10, 10, {maxWidth: 185, align: "justify"}); // to justify
// will export a pdf file with name export and above text.'export.pdf') }) 

The attached file will be exported on click of export.

Join Discussion

This site uses Akismet to reduce spam. Learn how your comment data is processed.