Image To PDF Converter using React Last Updated : 22 Mar, 2024 Comments Improve Suggest changes Like Article Like Report Image To PDF Converter using React is a web application that allows users to upload images and convert them into PDF documents. It uses React's state management and file handling capabilities to provide a user-friendly interface for image upload, display, deletion, and PDF generation. This application enhances productivity by simplifying the process of creating PDF files from images directly within the browser. Output Preview: Let us have a look at how the final output will look like Steps to Create Image To PDF project:Step 1: Create a new React JS project using the following command npx create-react-app <<Project_Name>>Step 2: Change to the project directory. cd <<Project_Name>>Step 3: Install the requires modules npm install jspdf,npm install file-saverProject Structure:The updated dependencies in package.json will look like this: "dependencies": { "@testing-library/jest-dom": "^5.17.0", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "file-saver": "^2.0.5", "html2canvas": "^1.4.1", "jspdf": "^2.5.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" },Approach to create Image to PDF Converter:Initialize a new React project using Create React App or your preferred method.Create a component to handle image uploads using <input type="file"> and FileReader API to read image files as data URLs.Use state to manage the uploaded images and display them in the UI as thumbnails or previews.Utilize a PDF library like jsPDF to dynamically generate a PDF document from the uploaded images. Map each image to a PDF page and add them to the document.Provide user actions such as deleting uploaded images, and include a button to trigger the PDF generation process.Example: This example to shows the conversion of image to pdf. CSS /* App.css */ body { margin: 0; padding: 0; box-sizing: border-box; background-color: white; font-family: 'PT Serif', serif; } .nav { padding: 0.5rem 1rem; background: white; border-bottom: 1px solid rgb(245, 244, 244); position: sticky; top: 0; z-index: 1; display: flex; justify-content: space-between; align-items: center; font-family: 'Kanit', sans-serif; } .logo { padding-left: 85px; font-size: 3rem; color: rgb(182, 34, 34); } .pdf-btn, .upload-btn { border: none; outline: none; background: #4f4c5e; color: white; border-radius: 8px; padding: 0.5rem 1rem; font-size: 1rem; margin-right: 1rem; cursor: pointer; } .container { margin: 2rem auto; padding: 0 1rem; } .image-preview { display: flex; flex-wrap: wrap; justify-content: center; } .image-item { margin: 1rem; position: relative; } .delete-btn { position: absolute; top: 0.5rem; right: 0.5rem; background: #f44336; color: white; border: none; border-radius: 50%; padding: 0.3rem; cursor: pointer; transition: background 0.3s; } .delete-btn:hover { background: #d32f2f; } /* Drop box styling */ .drop-box { border: 2px dashed #6a5858; border-radius: 5px; padding: 10rem; text-align: center; cursor: pointer; margin-top: 2rem; margin-left: 170px; margin-right: 200px; } .drop-box:hover { background-color: #f9f9f9; } .drop-text { font-size: 1rem; color: #888; } .drop-text:hover { color: #555; } .pdf { margin-left: 80px; } JavaScript import React, { useState } from 'react'; import './App.css'; import jsPDF from 'jspdf'; const App = () => { const [images, setImages] = useState([]); const handleImageUpload = (event) => { const files = event.target.files; const newImages = [...images]; for (let i = 0; i < files.length; i++) { const file = files[i]; const reader = new FileReader(); reader.onload = () => { newImages.push({ data: reader.result, name: file.name, }); setImages(newImages); }; reader.readAsDataURL(file); } }; const handleDrop = (event) => { event.preventDefault(); const files = event.dataTransfer.files; const newImages = [...images]; for (let i = 0; i < files.length; i++) { const file = files[i]; const reader = new FileReader(); reader.onload = () => { newImages.push({ data: reader.result, name: file.name, }); setImages(newImages); }; reader.readAsDataURL(file); } }; const handleDragOver = (event) => { event.preventDefault(); }; const handleDelete = (index) => { const updatedImages = [...images]; updatedImages.splice(index, 1); setImages(updatedImages); }; const generatePDF = () => { const doc = new jsPDF(); images.forEach((image, index) => { if (index > 0) { doc.addPage(); } doc.text(image.name, 10, 10); doc.addImage(image.data, 'JPEG', 10, 20, 180, 160); }); doc.save('converted_images.pdf'); }; return ( <div className="app"> <div className="nav"> <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20240320031658/pdf.png"> </img> <div className="logo"> Image to PDF Converter </div> <label htmlFor="image-upload" className="upload-btn"> Upload Images </label> <input type="file" id="image-upload" accept="image/*" multiple onChange={handleImageUpload} style={{ display: 'none' }} /> </div> <div className="container" onDrop={handleDrop} onDragOver={handleDragOver} > {images.length === 0 ? ( <div className="drop-box"> <span className="drop-text"> Drag and drop images here </span> <input type="file" id="image-upload-drop" accept="image/*" multiple onChange={handleImageUpload} style={{ display: 'none' }} /> </div> ) : ( <div className="image-preview"> {images.map((image, index) => ( <div key={index} className="image-item"> <img src={image.data} alt={image.name} /> <button className="delete-btn" onClick={() => handleDelete(index)}> Delete </button> <button className="pdf-btn" onClick={generatePDF}> Convert to PDF </button> </div> ))} </div> )} </div> </div> ); }; export default App; Steps to run the project: Step 1: Type the following command in terminal. npm startStep 2: Open web-browser and type the following URL http://localhost:3000/Output: Comment More infoAdvertise with us Next Article React Introduction A aakashya4h46 Follow Improve Article Tags : Project Web Technologies ReactJS Dev Scripter ReactJS-Projects Dev Scripter 2024 +2 More Similar Reads React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version 7 min read React FundamentalsReact IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() { 6 min read React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be 3 min read React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa 3 min read React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi 5 min read ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements 3 min read React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a 4 min read React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc. 5 min read ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. the When rendering a list, you need to assign a unique key prop to each element i 4 min read Components in ReactReact ComponentsIn React, components are reusable, independent blocks that define the structure and behavior of the UI. They accept inputs (props) and return elements that describe what should appear on the screen.Key Concepts of React Components:Each component handles its own logic and UI rendering.Components can 4 min read ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Example:JavaScriptimport 4 min read React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el 3 min read ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p 4 min read ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon 2 min read ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he 5 min read React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo 7 min read React HooksReact HooksReactJS Hooks are one of the most powerful features of React, introduced in version 16.8. They allow developers to use state and other React features without writing a class component. Hooks simplify the code, make it more readable, and offer a more functional approach to React development. With hoo 10 min read React useState HookThe useState hook is a function that allows you to add state to a functional component. It is an alternative to the useReducer hook that is preferred when we require the basic update. useState Hooks are used to add the state variables in the components. For using the useState hook we have to import 5 min read ReactJS useEffect HookThe useEffect hook is one of the most commonly used hooks in ReactJS used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.What is 4 min read Routing in ReactReact RouterReact Router is a library for handling routing and navigation in React JS Applications. It allows you to create dynamic routes, providing a seamless user experience by mapping various URLs to components. It enables navigation in a single-page application (SPA) without refreshing the entire page.This 6 min read React JS Types of RoutersWhen creating a React application, managing navigation between different views or pages is important. React Router is the standard library for routing in React, enabling seamless navigation while maintaining the Single Page Application (SPA) behaviour.What is React Router?React Router is a declarati 10 min read Advanced React ConceptsLazy Loading in React and How to Implement it ?Lazy Loading in React is used to initially load and render limited data on the webpage. It helps to optimize the performance of React applications. The data is only rendered when visited or scrolled it can be images, scripts, etc. Lazy loading helps to load the web page quickly and presents the limi 4 min read ReactJS Higher-Order ComponentsHigher-order components (HOC) are an advanced technique in React that is used for reusing component logic. It is the function that takes the original component and returns the new enhanced component.It doesnât modify the input component directly. Instead, they return a new component with enhanced be 5 min read Code Splitting in ReactCode-Splitting is a feature supported by bundlers like Webpack, Rollup, and Browserify which can create multiple bundles that can be dynamically loaded at runtime.As websites grow larger and go deeper into components, it becomes heavier. This is especially the case when libraries from third parties 4 min read React ProjectsCreate ToDo App using ReactJSIn this article, we will create a to-do app to understand the basics of ReactJS. We will be working with class based components in this application and use the React-Bootstrap module to style the components. This to-do list allows users to add new tasks and delete them by clicking the corresponding 3 min read Create a Quiz App using ReactJSIn this article, we will create a quiz application to learn the basics of ReactJS. We will be using class components to create the application with custom and bootstrap styling. The application will start with questions at first and then the score will be displayed at last. Initially, there are only 4 min read Create a Coin Flipping App using ReactJSIn this article, we will build a coin flipping application. In which the user can flip a coin and get a random result from head or tails. We create three components 'App' and 'FlipCoin' and 'Coin'. The app component renders a single FlipCoin component only. FlipCoin component contains all the behind 3 min read How to create a Color-Box App using ReactJS?Basically we want to build an app that shows the number of boxes which has different colors assigned to each of them. Each time the app loads different random colors are assigned. when a user clicks any of the boxes, it changes its color to some different random color that does not equal to its prev 4 min read Dice Rolling App using ReactJSThis article will create a dice-rolling application that rolls two dice and displays a random number between 1 and 6 as we click the button both dice shake and generate a new number that shows on the upper face of the dice (in dotted form as a standard dice). The numbers on the upper face are genera 4 min read Guess the number with ReactIn this article, we will create the guess the number game. In which the computer will select a random number between 1 and 20 and the player will get unlimited chances to guess the number. If the player makes an incorrect guess, the player will be notified whether the guess is is higher or lower tha 3 min read Like