want you to create website wher I can conver image to pdf and vice-versa. the user can…
- User
want you to create website wher I can conver image to pdf and vice-versa.
the user can see their download history from thier own local browser cookie where we store thier history. no any login/singup required.
Just html, css, tailwind css, bootstrap, js'
- Assistant
Below is a step-by-step guide to create a website that converts images to PDFs and PDFs to images, with download history stored in browser cookies. We'll use HTML, CSS, Tailwind CSS, Bootstrap, and JavaScript. For the conversion, we'll use libraries like
pdf-libfor PDF manipulation andFileSaver.jsfor downloading files.
Project Structure
image-pdf-converter/ │ ├── index.html # Main HTML file ├── styles.css # Custom CSS (if needed) ├── script.js # JavaScript logic └── README.md # Project documentation
Step 1: Setup HTML (
index.html)This file will contain the structure of the website, including file upload inputs, buttons, and a section to display download history.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image to PDF & PDF to Image Converter</title> <!-- Tailwind CSS --> <script src="https://cdn.tailwindcss.com"></script> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link rel="stylesheet" href="styles.css"> </head> <body class="bg-gray-100"> <div class="container mx-auto py-10"> <h1 class="text-4xl font-bold text-center mb-8">Image to PDF & PDF to Image Converter</h1> <!-- Image to PDF Section --> <div class="bg-white p-6 rounded-lg shadow-lg mb-8"> <h2 class="text-2xl font-semibold mb-4">Convert Image to PDF</h2> <input type="file" id="imageInput" accept="image/*" class="form-control mb-4"> <button id="convertImageToPdf" class="btn btn-primary w-full">Convert to PDF</button> <p id="imageToPdfStatus" class="mt-2 text-center"></p> </div> <!-- PDF to Image Section --> <div class="bg-white p-6 rounded-lg shadow-lg mb-8"> <h2 class="text-2xl font-semibold mb-4">Convert PDF to Image</h2> <input type="file" id="pdfInput" accept="application/pdf" class="form-control mb-4"> <button id="convertPdfToImage" class="btn btn-primary w-full">Convert to Image</button> <p id="pdfToImageStatus" class="mt-2 text-center"></p> </div> <!-- Download History Section --> <div class="bg-white p-6 rounded-lg shadow-lg"> <h2 class="text-2xl font-semibold mb-4">Download History</h2> <ul id="historyList" class="list-group"></ul> <button id="clearHistory" class="btn btn-danger mt-4">Clear History</button> </div> </div> <!-- Libraries --> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf-lib/1.17.1/pdf-lib.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js"></script> <!-- Custom JavaScript --> <script src="script.js"></script> </body> </html>
Step 2: Custom CSS (
styles.css)This file is optional but can be used to add custom styles if needed. For now, we'll rely on Tailwind CSS and Bootstrap.
/* styles.css */ body { font-family: 'Arial', sans-serif; }
Step 3: JavaScript Logic (
script.js)This file contains the logic for converting files, managing cookies, and updating the download history.
// Initialize PDF.js worker pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.min.js'; // Function to add a file to download history function addToHistory(fileName, fileType, timestamp) { const history = Cookies.get('downloadHistory') ? JSON.parse(Cookies.get('downloadHistory')) : []; history.push({ fileName, fileType, timestamp }); Cookies.set('downloadHistory', JSON.stringify(history), { expires: 7 }); // Expires in 7 days updateHistoryUI(); } // Function to update the download history UI function updateHistoryUI() { const historyList = document.getElementById('historyList'); const history = Cookies.get('downloadHistory') ? JSON.parse(Cookies.get('downloadHistory')) : []; historyList.innerHTML = ''; if (history.length === 0) { historyList.innerHTML = '<li class="list-group-item">No download history available.</li>'; return; } history.forEach(item => { const li = document.createElement('li'); li.className = 'list-group-item'; li.textContent = `${item.fileName} (${item.fileType}) - ${new Date(item.timestamp).toLocaleString()}`; historyList.appendChild(li); }); } // Function to clear download history document.getElementById('clearHistory').addEventListener('click', () => { Cookies.remove('downloadHistory'); updateHistoryUI(); }); // Image to PDF Conversion document.getElementById('convertImageToPdf').addEventListener('click', async () => { const imageInput = document.getElementById('imageInput'); const status = document.getElementById('imageToPdfStatus'); const file = imageInput.files[0]; if (!file) { status.textContent = 'Please select an image file.'; return; } status.textContent = 'Converting...'; try { const img = new Image(); img.src = URL.createObjectURL(file); await new Promise((resolve) => (img.onload = resolve)); const { PDFDocument } = PDFLib; const pdfDoc = await PDFDocument.create(); const page = pdfDoc.addPage([img.width, img.height]); const imgData = await fetch(img.src).then(res => res.arrayBuffer()); const imgType = file.type === 'image/png' ? 'png' : 'jpeg'; const embeddedImg = await pdfDoc.embedImage(imgData, { format: imgType }); page.drawImage(embeddedImg, { x: 0, y: 0, width: img.width, height: img.height }); const pdfBytes = await pdfDoc.save(); const blob = new Blob([pdfBytes], { type: 'application/pdf' }); const fileName = `converted-${Date.now()}.pdf`; saveAs(blob, fileName); status.textContent = 'Conversion successful! File downloaded.'; addToHistory(fileName, 'PDF', Date.now()); } catch (error) { status.textContent = 'Error during conversion. Please try again.'; console.error(error); } }); // PDF to Image Conversion document.getElementById('convertPdfToImage').addEventListener('click', async () => { const pdfInput = document.getElementById('pdfInput'); const status = document.getElementById('pdfToImageStatus'); const file = pdfInput.files[0]; if (!file) { status.textContent = 'Please select a PDF file.'; return; } status.textContent = 'Converting...'; try { const arrayBuffer = await file.arrayBuffer(); const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise; const page = await pdf.getPage(1); // Convert only the first page const viewport = page.getViewport({ scale: 2 }); const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; await page.render({ canvasContext: context, viewport }).promise; const imgData = canvas.toDataURL('image/png'); const fileName = `converted-${Date.now()}.png`; saveAs(imgData, fileName); status.textContent = 'Conversion successful! File downloaded.'; addToHistory(fileName, 'Image', Date.now()); } catch (error) { status.textContent = 'Error during conversion. Please try again.'; console.error(error); } }); // Initialize history UI on page load window.onload = updateHistoryUI;
Step 4: Explanation of Libraries Used
- PDFLib: Used for creating and manipulating PDFs (e.g., embedding images into a PDF).
- PDF.js: Used for rendering PDFs and converting them to images.
- FileSaver.js: Used to trigger file downloads in the browser.
- js-cookie: Used to manage browser cookies for storing download history.
Step 5: Running the Project
- Save all files in the project structure mentioned above.
- Open
index.htmlin a modern web browser (e.g., Chrome, Firefox). - Test the functionality by uploading an image or PDF and converting it. Check the download history section to see the stored history.
Step 6: Features of the Website
- Image to PDF: Upload an image (PNG, JPEG, etc.), convert it to a PDF, and download it.
- PDF to Image: Upload a PDF, convert the first page to an image (PNG), and download it.
- Download History: View a list of downloaded files with timestamps, stored in browser cookies.
- Clear History: Clear the download history from cookies.
Step 7: Notes and Limitations
- Browser Compatibility: Ensure you test the website in modern browsers, as some features (e.g., File APIs) may not work in older browsers.
- File Size: Large files may take longer to process, and very large PDFs may cause performance issues.
- Security: Since this is a client-side application, no data is sent to a server, ensuring user privacy.
- Cookies: The download history is stored in cookies, which have a size limit (typically 4KB). If the history grows too large, older entries may need to be removed.
Step 8: Deployment (Optional)
To make the website accessible online, you can host it on platforms like GitHub Pages, Netlify, or Vercel. Simply upload the project files to a repository or drag-and-drop them into the hosting platform.
This setup provides a fully functional, no-login-required website for image-to-PDF and PDF-to-image conversion with download history. Let me know if you need further assistance!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.