How I made Image to PDF converter tool in JavaScript
Tags: javascript, webdev, tutorial
Published: 2023-04-20 20:03:49

Have you ever needed to convert a bunch of images into a single PDF document? Maybe you have a collection of scanned documents, or you want to share some photos in a more organized way. Whatever the reason, this task can be time-consuming if done manually.


![Image to Pdf converter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rh722tbc9m4c65i7hhjj.png)



But don't worry, I got you covered! In this blog post, I'll share with you how I created a simple Image to PDF converter tool using JavaScript, HTML, and CSS.

But before you move further, if you want to try out the convert, do checkout https://codepen.io/vaib215/pen/WNaoMBr

## The Plan
To create our Image to PDF converter tool, we need to break down the plan into smaller steps:

- Allow users to select multiple images from their device.
- Display selected images on the webpage.
- Convert the images into a single PDF document.
- Allow the user to download the PDF document.

## The Code
### HTML
Let's start by creating the HTML structure. We'll create three main elements:

- A container to display selected images.
- A container to display the order of selected images.
- A button to trigger the conversion process.

```
    <header>
    <h1>Image to PDF Converter</h1>
  </header>
  <div class="container">
    <input type="file" id="fileInput" multiple>
    <button style="--clr:#008cba;--hov:#006080;" id="addImageButton">Add Images</button>
    <button style="--clr:#3e8d75;--hov:#3e8e41;" id="convertButton">Convert to PDF</button>
    <button style="--clr:#f44336;--hov:#ff6b6b;" id="clearButton">Clear Images</button>
    <div id="pdfDownloadLink"></div>
    <div id="imageContainer"></div>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
```

### CSS
Next, we'll add some basic CSS to make the page look good. We'll center the image container and the order container and add some padding to the body. Also, some style to make the UI better.

```
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}
header {
  background-color: #333;
  color: #fff;
  padding: 10px;
  text-align: center;
}
.container {
  margin: 20px auto;
  max-width: 800px;
  display: flex;
  flex-wrap: wrap;
}

.imageBox {
  width: 200px;
  height: 200px;
  margin: 10px;
  position: relative;
}
.imageBox img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.deleteButton:hover {
  background-color: #ff6b6b;
}
#imageContainer {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
#imageContainer img {
  max-width: 100%;
}
#pdfDownloadLink {
  margin: 20px auto;
  text-align:center;
  background: "red";
  width:100%;
}

#fileInput {
  display: none;
}
button{
  border: none;
  background: var(--clr);
  color: white;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 20px auto;
  cursor: pointer;
  border-radius: 5px;
}

button:hover{
  background: var(--hov);
}

.deleteButton {
  background-color: #f44336;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  position: absolute;
  top: -10px;
  padding: 0;
  right: 5px;
}
```

### JavaScript
Now, let's write some JavaScript code to handle the functionality of our Image to PDF converter tool. We'll start by creating some variables to store references to our HTML elements.

```
const imageContainer = document.getElementById('imageContainer');
const convertButton = document.getElementById('convertButton');
const pdfDownloadLink = document.getElementById('pdfDownloadLink');
const orderContainer = document.getElementById('orderContainer');
let imageFiles = [];
```

Next, we'll create a function to render the selected images in the UI.

```
const renderImages = () => {
  imageContainer.innerHTML = '';
  orderContainer.innerHTML = '';
  imageFiles.forEach((file, index) => {
    const imageElement = document.createElement('img');
    imageElement.src = URL.createObjectURL(file);
    imageElement.classList.add('image-item');
    imageElement.setAttribute('data-index', index);
    imageContainer.appendChild(imageElement);

    const orderInput = document.createElement('input');
    orderInput.type = 'text';
    orderInput.classList.add('order-input');
    orderInput.setAttribute('data-index', index);
    orderInput.value = index;
    orderContainer.appendChild(orderInput);
  });
};
```
This function loops through the `imageFiles` array and creates an image element and an order input element for each image file. We set the `src` attribute of the image element to a data URL created from the image file.

Next, we'll create a function to convert the images into a single PDF document.

```
const convertToPdf = () => {
const doc = new jsPDF();
imageFiles.forEach((file) => {
doc.addImage(file, 'JPEG', 10, 10, 190, 0);
if (imageFiles.indexOf(file) !== imageFiles.length - 1) {
doc.addPage();
}
});
pdfDownloadLink.href = doc.output('blobURL');
pdfDownloadLink.download = 'converted.pdf';
pdfDownloadLink.click();
};
```

This function creates a new `jsPDF` instance, loops through the `imageFiles` array, adds each image as a JPEG image to the PDF document, and adds a new page to the document for every image except the last one. Finally, we set the `href` and download attributes of the `pdfDownloadLink` element to the blob URL of the PDF document and the desired file name, respectively, and trigger a click on the element to download the PDF document.

Finally, we'll add some event listeners to our HTML elements to handle user interactions.

```
document.addEventListener('DOMContentLoaded', () => {
convertButton.addEventListener('click', convertToPdf);
});

document.addEventListener('change', (event) => {
if (event.target.type === 'file') {
imageFiles = Array.from(event.target.files);
renderImages();
}
});

document.addEventListener('keyup', (event) => {
if (event.target.classList.contains('order-input')) {
updateOrder();
}
});
```

We add a click event listener to the `convertButton` element to trigger the conversion process when the user clicks on it. We add a change event listener to the document to handle file input changes and call the `renderImages` function to update the UI when the user selects new images.

Code Link: https://codepen.io/vaib215/pen/WNaoMBr

## Conclusion
In this blog post, we learned how to create a simple Image to PDF converter tool using JavaScript, HTML, and CSS. By breaking down the task into smaller steps, we were able to create a functional tool that allows users to select multiple images, order them based on their preference, and convert them into a single PDF document. Feel free to try out the code and customize it to fit your needs.