html to pdf javascript

JavaScript has come a long way in serving more than just as a client-side scripting language. And today we can do all sorts of stuff that we would have usually done with any server-side language like Php, ASP.NET etc. Similar is the problem of exporting the HTML/CSS to a PDF document (HTML to pdf javascript).

Today there are a lot of solutions like html2canvas ( https://github.com/niklasvh/html2canvas ),

Jspdf ( https://github.com/MrRio/jsPDF ) or Pdfmake( https://github.com/bpampuch/pdfmake ) etc.

html2canvas” actually creates a screenshot and saves it as pdf using base64 , So the Pdf quality is not that good and “Jspdf” is better for creating table content Pdf using dynamic data but with “Pdfmake” you can actually export a proper Html/CSS Page into Pdf and the view content has to be static but the data can be dynamic and also the Pdf quality is good to compare to the above two.

But today we will discuss the Kendo UI API that has a feature to draw dom elements and export the same into a Pdf document.
I will show you guys step by step procedure to export the content of HTML/CSS into Pdf Document (HTML to pdf javascript).

Steps for export HTML to pdf javascript: 

First, you will need to add the library using a CDN ( http://kendo.cdn.telerik.com/2017.2.621/js/kendo.all.min.js ) in your HTML file.

 <script src="https://kendo.cdn.telerik.com/2017.2.621/js/jquery.min.js"></script> // dependency for Kendo UI API
 <script src="https://kendo.cdn.telerik.com/2017.2.621/js/jszip.min.js"></script>
 <script src="https://kendo.cdn.telerik.com/2017.2.621/js/kendo.all.min.js"></script>

 

Secondly, you will need to put whatever content in your web page using HTML/CSS which you want to export to the Pdf document.

<div class="wrapper" id="myCanvas">
<div class="wx-holder">
<div class="first-block wx-clearafter">
<div class="wx-right">
<div class="text-left bluecolor-text">
<h1 class="my-semibold" style="font-size: 26px;">Lorem Ipsum</h1>
<p class="bold-text my-semibold">Lorem Ipsum</p>
</div>
</div>
</div><!-- end wx-clearafter -->
<div>
<div class="">
<h2 class="my-medium">What is Lorem Ipsum?
</h2>
</div>
<div class="wx-holder">
<p class="p-class">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</P>
</div>
<div class="">
<h2 class="my-medium">Why do we use it?
</h2>
</div>
<div class="wx-holder">
<p class="p-class">It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</p>
</div>
</div>
<div>
<div class="">
<h2 class="my-medium">Why do we use it?</h2>
</div>
<div class="wx-holder">
<p class="p-class">It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</p>
</div>
<span class="prevent-split">
<div class="prevent-split">
<h2 class="my-medium"> Where does it come from?</h2>
</div>
<div class="wx-holder">
<p class="p-class">
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
</p>
</div>
</span>
</div>
<div class="wx-clearafter">
<div class="wx-leftmain orborder-right">
<font class="page-break" size=1pt face="arial" color=#FF2400>1 point arial type text</font><br>
<font class="page-break" size=2pt face="arial" color=#FF2400>2 point arial type text</font><br>
<font class="page-break" size=3pt face="arial" color=#FF2400>3 point arial type text</font><br>
<font class="page-break" size=4pt face="arial" color=#FF2400>4 point arial type text</font><br>
<font class="page-break" size=5pt face="arial" color=#FF2400>5 point arial type text</font><br>
<font class="page-break" size=6pt face="arial" color=#FF2400>6 point arial type text</font><br>
<font class="page-break" size=7pt face="arial" color=#FF2400>7 point arial type text</font> 
</div> 
</div> 
</div>
</div>   

Here, I am just using a bigger markup file so we can see the difference in Pdf Quality.

Note: The parent <div> tag has an id attribute.This id will later be used in a selector query by Kendo UI API.

Thirdly, we will write a function in script tag –


<script>
function ExportPdf(){ 
kendo.drawing
.drawDOM("#myCanvas", 
{ 
paperSize: "A4",
margin: { top: "1cm", bottom: "1cm" },
scale: 0.8,
height: 500
})
.then(function(group){
kendo.drawing.pdf.saveAs(group, "Exported.pdf")
});
}
</script>

 

Now, If you see in the above code I have used Kendo UI API and its one of the features that are DrawDom( drawing dom contents ).

The above code would alone give you the feature to export HTML/CSS to Pdf. Everything is correct about it but the quality of pdf still won’t be good and Kendo UI API has the solution to the problem by providing us the style sheet that will be applied on exported pdf.

But before applying the style sheet, Let me show you the exported document from above code –

html to pdf javascript

(Click on the image to see the Pdf document)
So, here are the links to the Kendo UI stylesheet-

  1. https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.common-material.min.css
  2. https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.material.min.css

 

Just add the above two stylesheets in the exported page and we are good to go.

Also, you can define the fonts for exported pdf. Kendo UI comes with some fonts by default for the exported Pdf but you can add custom fonts to your exported pdf as well by defining the following in your script tag –

<script> 
..... // code before this
kendo.pdf.defineFont({
"Montserrat-Regular" : "../../fonts/montserrat/Montserrat-Regular.ttf",
"Montserrat-Light" : "../../fonts/montserrat/Montserrat-Light.ttf",
"Montserrat-SemiBold" : "../../fonts/montserrat/Montserrat-SemiBold.ttf",
"Montserrat-Medium" : "../../fonts/montserrat/Montserrat-Medium.ttf",
"DejaVu Sans":
"http://cdn.kendostatic.com/2017.2.621/styles/fonts/DejaVu/DejaVuSans.ttf"
}); 
</script>

 

Another feature of exporting pdf with Kendo UI is the part of defining the template for Header and Footer of the document like so,

<script type="x/kendo-template" id="page-template">
<div class="page-template">
<div class="header">
// Company logo could be here 
</div>
<div class="footer" style="text-align: center">
<h2> #:pageNum# </h2> //footer has the page count
</div>
</div>
</script>

 

Now, The content of HTML could also go beyond one page. So Kendo UI supports multi-page Pdf export which is also supported in all the alternatives that I have mentioned at the start of this blog.

But the features which other’s don’t have or the advantage that Kendo UI has for exporting HTML/CSS to Pdf is that it could have automatic page break based on the height of the content or manual page break also, Which could be trigger by passing extra param named forcePageBreak while calling drawdom method.

Here is the code for that –

kendo.drawing
.drawDOM("#myCanvas", 
{ 
forcePageBreak: ".page-break", // add this class to each element where you want manual page break
paperSize: "A4",
margin: { top: "1cm", bottom: "1cm" },
scale: 0.8,
height: 500, 
template: $("#page-template").html()
})
.then(function(group){
kendo.drawing.pdf.saveAs(group, "Exported.pdf")
});
<div>
<div class="page-break">
<h2 class="my-medium">Why do we use it?</h2>
</div>
<div class="wx-holder">
<p class="p-class">It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</p>
</div>
</div>

Let’s see how the PDF looks now with all these features –

html to pdf javascript

(Click on the image to see the Pdf document)

 

Another feature that Kendo UI supports is keeping the elements intact or keeping them together, Let me show you a document for what I mean –

html to pdf javascript

(Click on the image to see the Pdf document)

HTML to pdf javascript:

If you will scroll down the above document you will see that the last paragraphs heading is on one page and its content in another. So, To resolve this kind of situations Kendo UI provides another param that can be passed to a drawDom method which is kept together.

Let’s see the code to understand –

kendo.drawing
.drawDOM("#myCanvas", 
{ 
forcePageBreak: ".page-break", // add this class to each element where you want manual page break
paperSize: "A4",
margin: { top: "1cm", bottom: "1cm" },
scale: 0.8,
height: 500, 
template: $("#page-template").html(),
keepTogether: ".prevent-split"
})
.then(function(group){
kendo.drawing.pdf.saveAs(group, "Exported.pdf")
});

Using keepTogether attribute in drawdom function of kendo and use that class name in your HTML wherever you want things to stick together and this will result in a document similar to the one below –
html to pdf javascript

(Click on the image to see the Pdf document)

The whole code above could be tried at Kendo UI dojo ( http://dojo.telerik.com/otugA )

 

Also, Read:

Understanding Elastic Search – How does it work?

Virtual Dom|Browser DOM what are these in React Js?

  1. Muy buen aporte estimado. Gracias.

    Quiero dejar como sentado que funciona con archivos de distintos proveedores como aws S3 y Azure , lo acabo de comprobar.

  2. This is great tutorial and it works. I implemented HTML to PDF download, and it was working fine, but few days ago on Chrome, Opera and IE11 I can’t download PDF, it stopped working, while on Mozilla Firefox it is working fine. Can you please suggest me how to fix this problem?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

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