Learn how to convert JPG images to PDF files using free PHP, JavaScript, and HTML code with Bootstrap styling. This guide includes full code examples and practical tips for Indian developers.

Introduction to JPG to PDF Conversion

Converting JPG images to PDF files is a common requirement in many web applications, especially for document management, portfolios, and reporting. Using PHP, JavaScript, and HTML combined with Bootstrap, you can create a seamless, responsive, and user-friendly interface for this conversion without relying on paid services.

This article provides free, full code examples for converting JPG to PDF using both server-side PHP and client-side JavaScript, styled with Bootstrap for a clean and modern look. Whether you are a beginner or an experienced developer from India looking for an easy-to-follow solution, this guide will help you implement JPG to PDF conversion efficiently.

Why Convert JPG to PDF?

  • Universal format: PDF is widely accepted and preserves formatting across devices.
  • Compact and secure: PDFs can be compressed and password-protected.
  • Multiple images: Combine several JPGs into a single PDF document.
  • Easy sharing: PDFs are easier to email and upload compared to multiple images.

Technologies Used

  • PHP: Server-side language to handle file uploads and PDF creation.
  • JavaScript: Client-side scripting for interactive file selection and PDF generation.
  • HTML & Bootstrap: Structure and styling for a responsive user interface.

Full Code Examples for JPG to PDF Conversion

1. PHP Code for JPG to PDF Conversion

This PHP script uses the FPDF library, which is free and easy to use for PDF generation. It accepts uploaded JPG files and converts them into a PDF.

<?php
require('fpdf.php');

if(isset($_FILES['images'])) {
    $pdf = new FPDF();
    $pdf->SetAutoPageBreak(false);

    foreach($_FILES['images']['tmp_name'] as $index => $tmpName) {
        $imageInfo = getimagesize($tmpName);
        if($imageInfo === false) continue; // Skip non-images

        $width = $imageInfo[0];
        $height = $imageInfo[1];
        $pdf->AddPage();

        // Calculate dimensions to fit A4
        $a4Width = 210; // mm
        $a4Height = 297; // mm
        $widthScale = $a4Width / $width;
        $heightScale = $a4Height / $height;
        $scale = min($widthScale, $heightScale);
        $newWidth = $width * $scale;
        $newHeight = $height * $scale;

        // Centering image
        $x = ($a4Width - $newWidth) / 2;
        $y = ($a4Height - $newHeight) / 2;

        $pdf->Image($tmpName, $x, $y, $newWidth, $newHeight);
    }

    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="converted.pdf"');
    $pdf->Output('D', 'converted.pdf');
    exit;
}
?>

2. HTML and Bootstrap Frontend for Uploading JPGs

This form allows users to select multiple JPG files and submit them to the PHP script above.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>JPG to PDF Converter</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container mt-5">
    <h2 class="mb-4">Convert JPG Images to PDF</h2>
    <form action="convert.php" method="post" enctype="multipart/form-data">
        <div class="mb-3">
            <label for="images" class="form-label">Select JPG Images</label>
            <input class="form-control" type="file" id="images" name="images[]" accept="image/jpeg" multiple required />
        </div>
        <button type="submit" class="btn btn-primary">Convert to PDF</button>
    </form>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

3. JavaScript (Client-Side) JPG to PDF Conversion Using jsPDF

If you prefer client-side conversion without uploading files, jsPDF is a popular open-source library that can convert images to PDF directly in the browser.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Client-side JPG to PDF</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container mt-5">
    <h2>Convert JPG to PDF (Client-side)</h2>
    <input type="file" id="imageInput" accept="image/jpeg" multiple class="form-control mb-3" />
    <button id="convertBtn" class="btn btn-success">Convert and Download PDF</button>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script>
    const { jsPDF } = window.jspdf;
    const input = document.getElementById('imageInput');
    const button = document.getElementById('convertBtn');

    button.addEventListener('click', () => {
        if(input.files.length === 0) {
            alert('Please select at least one JPG image.');
            return;
        }

        const pdf = new jsPDF();
        let promises = [];

        for(let i = 0; i < input.files.length; i++) {
            const file = input.files[i];
            const reader = new FileReader();

            const promise = new Promise((resolve) => {
                reader.onload = function(e) {
                    const imgData = e.target.result;
                    const img = new Image();
                    img.onload = function() {
                        const imgWidth = 210; // A4 width in mm
                        const pageHeight = 297; // A4 height in mm
                        const imgHeight = (img.height * imgWidth) / img.width;

                        if(i !== 0) pdf.addPage();
                        pdf.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight);
                        resolve();
                    };
                    img.src = imgData;
                };
                reader.readAsDataURL(file);
            });
            promises.push(promise);
        }

        Promise.all(promises).then(() => {
            pdf.save('converted.pdf');
        });
    });
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Summary Table: JPG to PDF Conversion

JPG to PDF Conversion
Aspect Details
Conversion Methods Server-side using PHP (FPDF), Client-side using JavaScript (jsPDF)
File Input Supports multiple JPG images via HTML file input
Output Format Single PDF file containing all selected JPG images
Styling Bootstrap framework for responsive and clean UI
Image Scaling Images are scaled to fit A4 size while maintaining aspect ratio
File Size Considerations PDF size depends on image resolution and compression; server-side allows more control
Browser Compatibility Client-side works in modern browsers; server-side requires PHP environment
Security Server-side allows validation and sanitization; client-side keeps files local
Use Cases Document submission, portfolios, reports, online converters
Cost Free open-source libraries and code; no paid services required

Conclusion

Converting JPG images to PDF files is straightforward with free tools and libraries available for both server-side and client-side implementations. Using PHP with FPDF is perfect for backend processing in Indian web hosting environments, while JavaScript with jsPDF offers an instant, no-upload solution directly in users' browsers. Combining these with Bootstrap provides a professional and responsive user interface.

Choose the method that best fits your project needs and infrastructure. The provided full code examples can be easily adapted or extended for more advanced features like password protection, multi-format support, or cloud integration.

Frequently Asked Questions (FAQs)

1. Can I convert multiple JPG images into one PDF file?

Yes, both the PHP and JavaScript methods shown here support multiple image uploads and combine them into a single PDF document.

2. Is it possible to convert JPG to PDF without uploading files to the server?

Yes, using client-side JavaScript with libraries like jsPDF, you can convert images to PDF directly in the browser without uploading files.

3. Do I need to install any software on the server to use the PHP code?

You need PHP installed along with the FPDF library, which is free and easy to include in your project folder.

4. How can I improve the quality of images in the PDF?

Use high-resolution JPG images and adjust scaling carefully. Server-side conversion allows more control over compression settings.

5. Can I customize the PDF layout or add text in the PDF?

Yes, libraries like FPDF and jsPDF support adding text, headers, footers, and other elements to customize the PDF layout.

6. Are these methods suitable for production use in Indian web applications?

Absolutely. Both PHP and JavaScript solutions are widely used and compatible with standard Indian web hosting environments and browsers.