How To Create HTML to PDF using javascript?

convert html to pdf

PDF’s are the most used file on the system in offline modes. Websites like e-commerce, bill payment or bookings provide a PDF download option for receipt of orders. These sites create PDF using dynamic data and be available immediately to the users.

What’s the issue?

Websites use dynamic data to show values. Values depend on different logics, sometimes a single page shows the different result for different users or options. In this article, we will explore the easiest way to provide download PDF option to users. If you have any favorite tool you have used in your project, please share or comments about them.

How to HTML to PDF?

To create pdf using javascript, we can use jsPDF jquery plugin. Using jsPDF we can set page size, orientation, and text. PDF generated using this plugin is also searchable and selectable.

Code Sample Live Example
var doc = new jsPDF({
  orientation: 'landscape',
  unit: 'in',
  format: [4, 2]
})

doc.text('Hello world!', 1, 1);
if (base64Img) {
	doc.addImage(base64Img, 'JPEG', data.settings.margin.left, 15, 10, 10);
}
doc.save('two-by-four.pdf');

jsPDF plugin issue & solution

Dynamic Content Issue

jsPDF provides script functions to add text and images in pdf object, but aligning them in the pdf file is very critical. As we need to mention top and left positions for elements, dynamic content creates issues due to its content height.

CSS Availability

jsPDF support very less css attributes like setFontSize, setTextColor, setFontStyle etc.

Solutions!

To resolve both issues we would suggest using another jquery plugin html2canvas. Html2canvas plugin enables us to capture screen from the current page. The plugin provides result in base64 format that can be added to jsPDF. Sample code is provided with an example below.

Code Sample Live Example
$(function(){
	$(window).load(function(){
		var pdf = new jsPDF();
		$('#page1').html2canvas({
			letterRendering: 1, allowTaint : true,useCORS: true,
			logging:true, 
			onrendered: function (canvas) {
				var _imgData = canvas.toDataURL("image/jpeg");
				pdf.addImage(_imgData, 'JPEG', 4, 0);	
				pdf.save("download.pdf");
			}
		});
	})	
});

Download the source code.