Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Build an Online Image-to-PDF Converter with HTML, CSS, JS, and NodeJS

Tags: code route server

An online image-to-PDF converter is a website that helps you convert your images to PDFs. This tool is useful because it provides an efficient way to store your images.In this tutorial, you'll learn how you can create your online image-to-pdf converter with HTML, CSS, JavaScript, and NodeJS.Before starting this project, you should have or know the following languages/libraries/frameworks:HTML, CSS, and JavaScript: You must have a basic knowledge of using HTML, CSS, and JavaScript to follow along with this tutorial. You should know how to create these files and link them together. You should know about fundamental HTML elements, core CSS selectors, JavaScript concepts, and the DOM.NodeJS and npm: You need to have npm and Node.js installed because we'll use them for installing the necessary packages for your project. Specifically, you must have a basic knowledge of how to import and use Nodejs built-in modules.Nodemon: Nodemon is an important Node package that’ll help you develop your project faster. It helps in restarting your Server when you make changes to the project.Express.js and express-generator: Express.js is the Node framework you’ll use to build the web server. Express-generator is a library that'll help you create the necessary files and folders for Express.js to run efficiently. You should know how to create a basic Express application.Express-session: This is an Express middleware library that'll help you manage the application sessions. You should know about the configurations of this library.Jade/Pug: This is a JavaScript templating engine that'll help you render the address of the uploaded images in an HTML file. You should know the basics of this library.PDFkit: This is a JavaScript library that we'll use to convert the images to PDF.Multer: This is a Node library that'll handle the file uploads.Sortablejs: This is a JavaScript drag-and-drop library that we'll use in the frontend for rearranging our images before they are converted to PDF.Finally, you must know how to create folders and files (with their appropriate extensions). You should know how to edit these files with a text editor.First, you need to create a folder and navigate to it with the CLI:Next, initialize it as a npm package so that you’ll be able to install all the necessary libraries you need.If everything goes well, there'll be a package.json file in your folder.The package.json should look like this:Next, we'll install express-generator like this:We'll choose jade as the default templating engine.The command above will set up all the necessary folders and libraries needed for Express.js to run efficiently.At the end of the installation, your project folder will look like this:When you check your package.json file, you'll see that Express.js, Jade, and some other libraries have been installed.Next, we'll install the Nodemon package globally.Finally, we'll install PDFkit, Multer, Sortablejs, and Express-session.Next, add a devstart script in your package.json. It'll allow Nodemon to restart your application when you make any changes to your JavaScript files.At the end of your installation, your package.json file should look like this:Next, you'll navigate to the project folder and start the application server.Once you get a success message, it means the server is already running.Open your web browser and type http://localhost:3000/ in the search bar.If everything goes well, this should be your result:Before writing the Code, let's go through an overview of the steps that we'll follow to build this project:First you'll define a route that returns the index HTML file when the root URL / is reached.Within your index HTML file, you'll create a form that accepts only image files (png, jpg) and then send it to the server at a defined route.When the server receives the images with Multer, it'll store them in a folder, store the address in a session store, and redirect the request to the root URL route which will render a Jade file containing the address of the uploaded images.Within the Jade file, you'll activate Sortablejs so that the user can rearrange the images before converting to PDF. There'll also be a 'convert to PDF' button which will send the address of the sorted image to the server /pdf route.When the /pdf route receives the images, you'll use PDFkit to convert the images to PDF. Then you'll send the address of the converted PDF.When the user clicks on the PDF link, the file will be downloaded to the user's device.First, we'll be creating a route that sends an index.html file when the root URL (/) is reached.Here is the simple flowchart of this operation:First, open your routes/index.js file and create a route that returns an HTML file.Replace all the code in the routes/index.js file with this:From the code above, we included the express library and activated the express.Router() function. The path module was also included because it'll be used for describing the file paths.Then we defined a route method that'll handle all the GET requests directed at the root URL /. Anytime the route method receives a request it'll use the res.sendFile() method to send an index.html file back to the user.The __dirname variable and path.join() method used within res.sendFile(...) method helps us precisely specify the address of the index.html file.Next, create an html folder within the public folder and add an index.html page to it.This is how your public folder should look like:Next, create an index.html file in your public/html folder and add this code to it:If your server is still running, go to https://localhost:3000/ in your web browser.This should be the result:If you haven't started your server, navigate to your project's directory (cd img2pdf) and run this command:In this section, I'll be explaining how to upload images to the server.Here is the simple flowchart for this operation:Here's what's going on:While your server is still running, replace the content in your public/html/index.html file with this:In the code above, we linked some CSS files (styles.css and index.css) to the document. We also created a form element that sends a POST request to the /upload route. The form element has an enctype of multipart/form-data (without it, our server can't receive the images).Within the form element, there's an input element that'll help us get the files from the device. The input has a name attribute with the value of images (which will be used by multer to identify the images). It has been configured to accept multiple image files (with .png or .jpg extensions).There's also an input element that acts as the submit button. It'll be used to trigger the file upload request.Then there's the script element that contains some JavaScript code that adds interactivity to the HTML document.Create a style.css file in your public/stylesheets folder and add this CSS code to it:The CSS code above defines the overall layout of your website.Next, create an index.css file in your public/stylesheets folder and add this code to it:The CSS code above defines the specific styling of the index.html elements.Next, you'll open your routes/index.js file and create an /upload route that'll receive the image files, store them in a folder, store the filenames in the session store, and redirect the request to the root URL.First, we need to edit the app.js file and activate express-session.Add this code to your app.js file:This is how your app.js file should look like:Open your routes/index.js file and create a route that'll receive the image filenames, store them in a session and redirect to the root URL:From the code above, we included the Multer library. Then we used the multer.diskStorge() method to describe where the image files will be stored and how they should be renamed.Also, we created a fileFilter function to ensure that only png and jpg files are stored by the server. If the user sends any file that isn't PNG or JPG, an error page will be displayed with the message "Only png and jpg files are accepted".Next, we created a route method that listens to POST requests directed at the /upload route.Within this route method, we included the upload.array('images') method which tells mutler to only store files whose name is images (according to HTML input element ).After that, we extracted the filenames from the req.files property and stored them in the session store. Finally we redirect the request to the root URL route.In the routes/index.js file, edit the root URL route so that it'll render an index.jade file if the session stores the image filenames.From the code above, whenn the route URL route receives any request, it first checks if there is an imagefiles property stored in the session store. If there isn't, it sends the index.html file. But if there is, an index.jade file containing the image filenames will be sent.Finally, go to the views/index.jade file and edit it so that it'll render the uploaded images in HTML:The code above is written in Jade syntax, when the server renders it, it'll be in form of an HTML document.Note: make sure to do the indentation of your content in Jade/Pug with either the space key or tab key, not both.When you run or restart your server (rs with Nodemon), go to http://localhost:3000/ and restart the upload process (from selecting the files to clicking the upload button).You should see an HTML page containing the images you uploaded.Here's my result:In this section, I'll be explaining how you can allow the user to rearrange their images and convert them to a PDF.Here is the simple flowchart for this operation:Here's what's going on:In the views/index.jade file, we'll be using Sortablejs to sort the images.Replace the content in your index.jade file with this:The code above is a Jade file that'll be rendered as an HTML document. It contains the document metadata (including the link and style elements that connects to CSS and Javscript files), the image elements, the hyperlinks, and some other HTML elements.Next, create a public/stylesheets/index-view.css file and add this code to it:Next, navigate to the node_modules/sortablejs/modular folder and copy the sortable.core.esm.js file to the public/javascripts folder.Then create a public/javascripts/sort.js file.You'll add some code that'll activate Sortablejs and send the sorted filenames to the server for conversion:From the code above, we imported Sortablejs core JavaScript file and activated it on the parent element of the img elements.When the Convert to PDF button is clicked, we extracted the image filenames from the img elements and sent it as a POST request to the server.When the browser receives the server response, we attached the link to the download button so that when the user clicks on it, the PDF document will be downloaded on the user's device.Next, in your routes/index.js file, you'll create a /pdf route that'll receive the sorted filenames and convert them to PDF.First create a pdf folder in the public folder and add these code to your routes/index.js file:From the code above, we included pdfkit and created a route method that responds to POST requests directed at the /pdf URL. Within this route method, we used pdfkit to convert all the images to PDF. Finally, we sent the address of the PDF document back to the document.When you restart the server, navigate to http://localhost:3000/ in your web browser, and restart the file upload process. You'll able to convert your images to PDF.Here's a YouTube video describing the entire process:In this section, we'll be creating a functionality that allows the user to cancel the existing file upload project and create a new one.Remember that there's a New + button in our views/index.jade that points to the /new route.Now we'll be writing the route in our routes/index.js file.Here is the simple flowchart for this operation:Here's what's going on:Add this code to your routes/index.js file:From the code above, when the /new route receives a GET request, it'll delete the images stored in folder and session store. After that, it'll redirect the request to the root URL.When you navigate to http://localhost:3000/, upload some images, and cancel the existing file upload process, you'll see that the images were deleted from the folder and you were redirected to the homepage.With the code above, you've been able to create an online Image-to-PDF converter. Congrats!As you know, software development is a continuous process. So you can try implementing some additional functionalities (such as security, input validation, and so on) to the project.You can check out my GitHub repo for the complete source code.If you have any questions for me, you can check my freeCodeCamp profile for my contact details. I'll reply as quick as possible!Bye for now.I'm a software developer and a technical writer. I love writing about exciting technologies. Email: [email protected] Twitter: @GidtheCoder If you read this far, tweet to the author to show them you care. Tweet a thanks Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons - all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff. You can make a tax-deductible donation here.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

How to Build an Online Image-to-PDF Converter with HTML, CSS, JS, and NodeJS

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×