Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Sitemap
Menu

jsPDF Tutorial to Embed HTML Hyperlinks in PDF Documents in Javascript

Posted on December 16, 2022

 

 

Welcome folks today in this blog post we will be looking how to embed hyperlinks in pdf document using jspdf library in javascript. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to include the jspdf library cdn as shown below

 

 

1
2
3
4
5
6
7
8
9
10
<!doctype>
<html>
<head>
   <title>jsPDF Convert PDF to Base64 String</title>
   <script type="text/javascript" src="  https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
</body>
</html>

 

 

Now we need to add the div tag where we will have the sample html which contains some paragraph and heading of text. We have also some url or hyperlink. And also we have the button to trigger the export conversion of html to pdf

 

 

1
2
3
4
5
6
7
8
9
10
<div id="content">
        <h3>Generate PDF files in client-side JavaScript</h3>
  
   <p>href="https://parall.ax/products/jspdf#"</p>
   <p>Or refer to the YouTube video: https://www.youtube.com/watch?v=CnprxD_sJFE<p>
   </div>
  
   <div id="editor"></div>
  
   <button id="cmd">Generate PDF</button>

 

 

Now we need to write the javascript code where we will convert the html to pdf

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};
 
$('#cmd').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});

 

 

As you can see we are binded the onclick listener to the button using some jquery. And inside it we are using the fromHTML() method in which we are passing the content of the html which contains also the hyperlinks of the html. And then we are saving the result as the pdf document using the save() method.

 

 

 

Recent Posts

  • Build a Fixed Deposit Interest Calculator Using Amount and Time in Browser Using HTML5 & Javascript
  • How to Download Files From URL in Node.js Using Node-Downloader-Helper Library
  • Angular 10 Image Carousel and Video Gallery Lightbox Modal Slider Using ng-image-slider Library
  • React Unsplash Api Photo Search App
  • React Form Validation Using Formik and Yup
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • javascript
  • Koajs
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme