jsPDF + Html2Canvas Tutorial to Add Arabic Custom Font inside PDF Document in Javascript Full Project For Beginners

jsPDF + Html2Canvas Tutorial to Add Arabic Custom Font inside PDF Document in Javascript Full Project For Beginners

 

 

Welcome folks today in this post we will be adding arabic custom font inside pdf document with the help of jspdf and html2canvas library. All the source code of the application is shown below.

 

 

 

 

Get Started

 

 

 

In order to get started you need to add the following libraries which are jspdf and html2canvas we will be adding their cdn. So make a index.html file and copy paste the following code to include the cdn.

 

 

<!DOCTYPE html>
<html>
  <head>
    <title>jsPDF Arabic Font Example</title>
  </head>
  <body>
    
</body>
  <script src="  https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
  <script src="  https://unpkg.com/html2canvas@1.0.0-rc.5/dist/html2canvas.js"></script>
</html>

 

 

Now we will add a div element where we will add the arabic text to convert to pdf. So make this div tag and give a unique id to it

 

<div id="divIdToPrint">
          <h1>مرحبا اسمي جوتام</h1>
      </div>

 

 

So you can see we have added a simple h1 tag and inside it we have written some arabic text. And now we need to include some custom javascript to build the application

See also  Build a Youtube API Video Thumbnail Extractor or Grabber From URL in Vanilla Javascript Full Project For Beginners

 

 

<script>
      const input = document.getElementById('divIdToPrint');    
html2canvas(input)
      .then((canvas) => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF();
        pdf.addImage(imgData, 'PNG', 0, 0);
        pdf.save("download.pdf");  
  });
  </script>

 

 

So now if you open the index.html file you will see the following result

 

 

 

 

 

 

Full Source Code

 

 

 

 

<!DOCTYPE html>
<html>
  <head>
    <title>jsPDF Arabic Font Example</title>
  </head>
  <body>
      <div id="divIdToPrint">
          <h1>مرحبا اسمي جوتام</h1>
      </div>
</body>
  <script src="  https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
  <script src="  https://unpkg.com/html2canvas@1.0.0-rc.5/dist/html2canvas.js"></script>
  <script>
      const input = document.getElementById('divIdToPrint');    
html2canvas(input)
      .then((canvas) => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF();
        pdf.addImage(imgData, 'PNG', 0, 0);
        pdf.save("download.pdf");  
  });
  </script>
</html>

 

Leave a Reply