Skip to Content
convert html div to pdf using jquery
php code / August 29, 2021

In our past instructional exercise, you have figured out how to make PDF in PHP. In this instructional exercise, you will figure out how to change HTML over to PDF utilizing JavaScript.
I will include jsPDF and html2canvas library just before end of body tag.
PDF creation is quite possibly the main component of web applications. Now and then we need to carry out to change over HTML record into PDF document. Changing HTML over to PDF isn’t appears to be simple however with JavaScript it’s simpler than the worker side execution.

So here in this instructional exercise, we will execute to change over HTML record to PDF with JavaScript. We will utilize jsPDF library from JavaScript. The jsPDF is the best library to make PDF on the customer side. While making PDF from HTML, it require reliance on html2canvas when use html strategy.

Step1: Include Bootstrap, jQuery and jsPDF Library

<link rel="stylesheet" href="">
<script src=""></script>
<script src=""></script>

I will include jsPDF and html2canvas library just before end of body tag.

<script src=""></script>
<script src=""></script>
<script src="js/convert.js"></script>

Step2: Create HTML Form with File Input

<form name="foo" method="post" class="input-form" enctype="multipart/form-data">
<div style="margin-bottom: 25px" class="input-group">
<label class="form-label">Upload HTML file: </label> 
<input type="file" id="fileUpload" name="file" class="form-control" accept=".html,.htm">
<div class="preview">
<div id="previewHtmlContent"></div>
<div style="margin-bottom: 25px" class="input-group">
<input type="button" value="Show Preview" class="btn btn-info" id="previewHtml"><span id="error-message" class="error"></span>
<input type="button" value="Create PDF" class="btn btn-info hidden" id="convertHtmlToPDF">

Ste3: Preview HTML File

$(document).on('click', '#previewHtml', function(){previewHTMLFile(); }); function previewHTMLFile() { var filePath = $('#fileUpload').get(0).files[0]; var fileContents; $("#error-message").html(""); $("#fileUpload").css("border", "#a6a6a6 1px solid"); if ($(filePath).length != 0) { var reader = new FileReader(); reader.onload = function(e) { fileContents =; $(".preview").show(); $("#previewHtmlContent").html(fileContents); $("#previewHtml").addClass('hidden'); $("#convertHtmlToPDF").removeClass('hidden'); } reader.readAsText(filePath); } else { $("#error-message").html("required.").show(); $("#fileUpload").css("border", "#d96557 1px solid"); } } 

Step4: Convert HTML File to PDF

$(document).on('click', '#convertHtmlToPDF', function(){
function converHTMLToPDF() {
const { jsPDF } = window.jspdf;
var pdf = new jsPDF('l', 'mm', [1200, 1210]);
var pdfjs = document.querySelector('#previewHtmlContent'); 
pdf.html(pdfjs, {
callback: function(pdf) {"output.pdf");
x: 10,
y: 10
No comments yet, take the initiative.

Leave a Reply

Your email address will not be published.

PHPCODE © 2023