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

<head>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/" crossorigin="anonymous"></script>
</head>
<body>
<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>
</body>

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.setFontSize(22);
     doc.setTextColor(0, 0, 255);
     doc.setFont("helvetica");
     doc.setFontStyle("bold");
     doc.text(demo, 10, 10, {maxWidth: 185, align: "justify"}); // to justify
// doc.save will export a pdf file with name export and above text.
doc.save('export.pdf') }) 

The attached file will be exported on click of export.

Leave a Reply

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