I Love PDF Like Website Development | How to Develop Image to PDF Converter in HTML

You are currently viewing I Love PDF Like Website Development | How to Develop Image to PDF Converter in HTML

Introduction

PDF (Portable Document Format) is a kind of documents which is very popular in the present time. These types of documents are very useful in many kinds of works. People convert their documents, spreadsheets or presentations into PDF files and send them to any one around the world or upload them into websites.

PDF files are very easy to share. Anyone can share these documents easily and these documents can be easily accessed from any kind of devices like Smart Phones, Laptops, Tablets etc. We can print PDF files very easily. We do not require to set any margin to take the printout of a PDF file.

Sometimes, we may need to convert image files into a PDF file. In such kinds of tools, the user will select the images to convert into PDF then on clicking the convert button, the image files get converted into a PDF file.

For such kinds of Conversion, there is a very well known website “I Love PDF”. Many people use this website to convert their image files into PDF files or many other PDF related operations. This awesome website provides so many PDF tools like PDF Converter, PDF Splitter, PDF Joiner, PDF Cropper etc.

Here, I will explain the steps to create your own image to pdf converter with the help of HTML and JavaScript. You can create a similar website like “I Love PDF”. You can create this tool website very easily and embed this into your website. People will visit your website frequently to use this amazing tool. Because, people use this tool in a daily manner.

Use of I Love PDF Like Websites

People use such websites frequently. Because, PDF documents are daily usable documents. Most of the users want to send images after converting and stitching them into one PDF file. For this purpose, people use such kinds of online tools.

For example, I am going to take some pics and send them to someone through email. In this situation, I can take the pictures one by one and send them to that person, Or instead of that, I can take all the pictures and convert them into one PDF file. Thus, I can complete my work by sending only one file. It is more easier and simpler than the 1st option.

So, people prefer to convert images into PDF before sending that to anywhere.

Earning Strategy from I Love PDF Like Websites

People use PDF documents for all kinds of works like official, education, projects etc. So, most of the times, they need to convert images into PDF. In this way, people will visit in such websites more and more. As the number of visits increase, your income will also increase. In this way, you can generate a passive income for a long time.

Requirement to Develop a Website Like I Love PDF

To develop such a website, you will need a domain name and a hosting. This is not a very big investment. You can start with shared hosting. This will not cost so much. Choice of a good domain name is very important. Try to choose it by keeping a match with your keyword. To buy hosting and domain in a cheap rate, you can choose hostinger. You may visit hostinger official website from here.

Along with hosting, you will need a little bit of programming (coding) knowledge to develop this kind of website. You can develop your website with WordPress. After that, you can embed the image to pdf converter code into it. In this way, you can save your time and effort.

For the development, you will need HTML, PHP, CSS, JavaScript and JQUERY. In this tutorial, I will give the whole code. You just need to put them in to the appropriate spaces.

Method of Developing I Love PDF Like Website

Main Page (index.php)

First of all, you need to create the design of index.php page. For this purpose, we need HTML and CSS. In the index.php page, I have added an input file control with multiple file attribute. A div has been added under the input file control. The div will display all the images selected by the user to create the PDF file. Then, I have added a button through which users will convert the images into a PDF file and save it to a local drive.

The HTML code is given below –

<!DOCTYPE html>
<html>
<head>
	<title>Image to PDF Converter</title>
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
	<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
	<script src="http://localhost/class16/html2pdf/dist/html2pdf.bundle.min.js"></script>
</head>
<body bgcolor="white">
	<center>
		<h2>Image to PDF Converter</h2>
		<form method="post">
			<input type="file" name="file" id="file" accept="image/*" multiple>
			<p>
			<div class="images">
				
			</div>
		</form>

		<p>
		<div class="print"></div>
		<button class="btn" onclick="clickFun()">Convert and Download the PDF</button>
		<div class="main">
			<div class="pdf">
				
			</div>
		</div>
	</center>
</body>
</html>

The CSS Styling code for the index.php file is given below –

<style type="text/css">
		.images{
			display: flex;
			flex-direction: row;
			flex-flow: row wrap;
			align-items: center;
			overflow: hidden;
			justify-content: center;
			width: 600px;
			height: auto;
			min-height: 120px;
			border: 1px solid #888;
			padding-bottom: 5px;
		}
		.btn{
			width: 600px;
			height: 30px;
			color: #fff;
			background: #1F8298;
			cursor: pointer;
			outline: none;
			border: 0;
		}
		.btn:active{
			background: #244F58;
		}
		.main{
			display: none;
		}
		.pdf{
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			width: auto;
			height: auto;
			overflow-y: auto;
			overflow-x: hidden;
			border: 0px solid #888;
			margin-top: 20px;
		}

</style>

The HTML page looks like this –

i love pdf

Upload PHP File (upload.php)

Now, we need to create the upload.php file for uploading the image files to create a pdf file. Upload file i.e. upload.php file will collect the form data and upload the image file into images folder in server. I have created a random number function rand() to give a random number to every uploaded image file. The PHP function move_uploaded_file() finally upload the selected file(s) into the server. You need to create a folder with name images in the location of your source file. This folder will hold all the images that your visitors upload into your website to convert them into PDF.

The PHP code for upload.php is given below –

<?php
//upload.php
if($_FILES["file"]["name"] != '')
{
 $test = explode('.', $_FILES["file"]["name"]);
 $ext = end($test);
 $id = rand(1000, 9999);
 $name = $id . '-image' . '.' . $ext;
 $location = './images/' . $name;  
 move_uploaded_file($_FILES["file"]["tmp_name"], $location);
 echo $location;
}
?>

Addition of JQUERY Code for Uploading Files(s)

Now, we need to add the JQUERY code to the index.php file to send the form data to upload.php file and to receive the output from it. Before adding the code, we should add the CDN in the index.php file. To get the CDN, you can visit here. We need to copy the minified code for the latest CDN and paste it within <head> and </head> tags.

The JQUERY code is to be pasted before </body> tag. This set of code will help to send the form data and to receive the output from upload.php file.

The JQUERY code is given below –

<script type="text/javascript">
		$(document).ready(function(){
         $(document).on('change', '#file', function(){
         	var file = document.getElementById("file");
         	for(var i=0; file.files.length; i++){
         		  var name = document.getElementById("file").files[i].name;
		          var form_data = new FormData();
		          var ext = name.split('.').pop().toLowerCase();
		          if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1) 
		          {
		           alert("Invalid Image File");
		          }
		          var oFReader = new FileReader();
		          oFReader.readAsDataURL(document.getElementById("file").files[i]);
		          var f = document.getElementById("file").files[i];
		          var fsize = f.size||f.fileSize;
		          if(fsize > 2000000)
		          {
		           alert("Image File Size is very big");
		          }
		          else
		          {
		           form_data.append("file", document.getElementById('file').files[i]);
		           $.ajax({
		            url:"upload.php",
		            method:"POST",
		            data: form_data,
		            contentType: false,
		            cache: false,
		            processData: false,
		            beforeSend:function(){
		             
		            },   
		            success:function(data)
		            {
		             document.getElementsByClassName("images")[0].innerHTML += "<img src='" + data + "' height='100' width='100' style='margin-left: 5px; margin-top: 5px;'/>";
		             document.getElementsByClassName("pdf")[0].innerHTML += "<div style='min-height: 29.7cm; min-width: 20cm; background-image:url(" + data + "); background-size: contain; background-repeat: no-repeat;'></div>";
		            }
		           });
		          }
		        }
            });
        });
</script>

After uploading images, the page will look like this –

Adding JavaScript Code to Convert Images into PDF

For converting the images into a PDF document, we need html2pdf package. This package should be extracted and uploaded into the location of your source file. You can download the package from here. After pasting the folder in to the proper location, you need to connect the minified file of html2pdf with index.php file as shown in the above HTML code.

In this tutorial, all the images are injected inside a div and that div is getting converted into a single PDF. To do so, we need to add a set of JavaScript code to set/alter the functionalities of html2pdf.

The whole JavaScript code is given below –

<script type="text/javascript">
		function clickFun(){
			const element = document.getElementsByClassName('pdf')[0];
			
			var opt = {
					  margin:       0,
					  filename:     'myfile.pdf',
					  image:        { type: 'jpeg', quality: 0.98 },
					  html2canvas:  { scale: 2 },
					  jsPDF:        { unit: 'in', format: 'a4', orientation: 'portrait' }
					};
			html2pdf().from(element).set(opt).save();

		}
		
</script>

Overall HTML Code

The whole HTML code is given below –

<!DOCTYPE html>
<html>
<head>
	<title>Image to PDF Converter</title>
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
	<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
	<style type="text/css">
		.images{
			display: flex;
			flex-direction: row;
			flex-flow: row wrap;
			align-items: center;
			overflow: hidden;
			justify-content: center;
			width: 600px;
			height: auto;
			min-height: 120px;
			border: 1px solid #888;
			padding-bottom: 5px;
		}
		.btn{
			width: 600px;
			height: 30px;
			color: #fff;
			background: #1F8298;
			cursor: pointer;
			outline: none;
			border: 0;
		}
		.btn:active{
			background: #244F58;
		}
		.main{
			display: none;
		}
		.pdf{
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			width: auto;
			height: auto;
			overflow-y: auto;
			overflow-x: hidden;
			border: 0px solid #888;
			margin-top: 20px;
		}

	</style>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
	<script src="http://localhost/class16/html2pdf/dist/html2pdf.bundle.min.js"></script>
	<script type="text/javascript">
		function clickFun(){
			const element = document.getElementsByClassName('pdf')[0];
			
			var opt = {
					  margin:       0,
					  filename:     'myfile.pdf',
					  image:        { type: 'jpeg', quality: 0.98 },
					  html2canvas:  { scale: 2 },
					  jsPDF:        { unit: 'in', format: 'a4', orientation: 'portrait' }
					};
			html2pdf().from(element).set(opt).save();

		}
		
	</script>
</head>
<body bgcolor="white">
	<center>
		<h2>Image to PDF Converter</h2>
		<form method="post">
			<input type="file" name="file" id="file" accept="image/*" multiple>
			<p>
			<div class="images">
				
			</div>
		</form>

		<p>
		<div class="print"></div>
		<button class="btn" onclick="clickFun()">Convert and Download the PDF</button>
		<div class="main">
			<div class="pdf">
				
			</div>
		</div>
	</center>

	<script type="text/javascript">
		$(document).ready(function(){
         $(document).on('change', '#file', function(){
         	var file = document.getElementById("file");
         	for(var i=0; file.files.length; i++){
         		  var name = document.getElementById("file").files[i].name;
		          var form_data = new FormData();
		          var ext = name.split('.').pop().toLowerCase();
		          if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1) 
		          {
		           alert("Invalid Image File");
		          }
		          var oFReader = new FileReader();
		          oFReader.readAsDataURL(document.getElementById("file").files[i]);
		          var f = document.getElementById("file").files[i];
		          var fsize = f.size||f.fileSize;
		          if(fsize > 2000000)
		          {
		           alert("Image File Size is very big");
		          }
		          else
		          {
		           form_data.append("file", document.getElementById('file').files[i]);
		           $.ajax({
		            url:"upload.php",
		            method:"POST",
		            data: form_data,
		            contentType: false,
		            cache: false,
		            processData: false,
		            beforeSend:function(){
		             
		            },   
		            success:function(data)
		            {
		             document.getElementsByClassName("images")[0].innerHTML += "<img src='" + data + "' height='100' width='100' style='margin-left: 5px; margin-top: 5px;'/>";
		             document.getElementsByClassName("pdf")[0].innerHTML += "<div style='min-height: 29.7cm; min-width: 20cm; background-image:url(" + data + "); background-size: contain; background-repeat: no-repeat;'></div>";
		            }
		           });
		          }
		        }
            });
        });
	</script>
</body>
</html>

Conclusion

PDF files are very useful and easy to use in the present time. People use PDF files for sending and printing documents. You can convert any kind of documents into PDF file. So, it is a very good idea to work with PDF tools. This will give you a lot of traffic in your website and enough income sources.

Thank you.

You Also can Read

QR Code Generator in HTML Using JavaScript

Develop Age Calculator with HTML5 and PHP

Custom Popup in HTML with JavaScript and CSS

Leave a Reply