JPG to PDF Convert PHP Code with HTML and Bootstrap - Full Example

Are you looking for a simple way to convert JPG to PDF using PHP? In this article, you’ll find a complete working solution using PHP, HTML, and Bootstrap. Whether you're building a document conversion tool or just exploring how to convert image files into PDF format in PHP, this tutorial will help you step by step.


✅ Features of This JPG to PDF Converter

  • Upload JPG file

  • Convert it into PDF

  • Bootstrap UI for mobile-friendly design

  • Easy-to-use PHP backend with FPDF library


🧑‍💻 Requirements

  • PHP 7 or above

  • Apache/Nginx server (or use XAMPP/WAMP)

  • FPDF Library (free and open-source)


📁 Folder Structure

pgsql
jpg-to-pdf/ ├── index.php ├── convert.php ├── uploads/ └── fpdf/ └── fpdf.php

🔔 Note: Download FPDF library from https://www.fpdf.org/ and place fpdf.php inside fpdf/ folder.


🧩 Step 1: Create index.php (HTML Form with Bootstrap)

php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JPG to PDF Converter in PHP</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body class="bg-light"> <div class="container mt-5"> <div class="card shadow rounded"> <div class="card-body"> <h3 class="mb-4 text-center">JPG to PDF Converter using PHP</h3> <form action="convert.php" method="post" enctype="multipart/form-data"> <div class="mb-3"> <label for="image" class="form-label">Select JPG Image</label> <input class="form-control" type="file" name="image" accept=".jpg,.jpeg" required> </div> <> </form> </div> </div> </div> </body> </html>

🧩 Step 2: Create convert.php (PHP Conversion Code)

php
<?php require('fpdf/fpdf.php'); if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) { $image = $_FILES['image']['tmp_name']; // Create PDF $pdf = new FPDF(); $pdf->AddPage(); // Get image dimensions list($width, $height) = getimagesize($image); $pageWidth = 210; $pageHeight = 297; // Resize if image is larger than A4 $w = ($width / $height > $pageWidth / $pageHeight) ? $pageWidth : ($width / $height) * $pageHeight; $h = ($height / $width > $pageHeight / $pageWidth) ? $pageHeight : ($height / $width) * $pageWidth; $x = ($pageWidth - $w) / 2; $y = ($pageHeight - $h) / 2; $pdf->Image($image, $x, $y, $w, $h); $outputName = 'converted_' . time() . '.pdf'; $pdf->Output('D', $outputName); // 'D' forces download } else { echo "Image upload failed. Please try again."; }

💡 How It Works

  1. User uploads a .jpg file through the HTML form.

  2. PHP script (convert.php) receives the image.

  3. FPDF generates a PDF file with the image centered on an A4 page.

  4. PDF file is downloaded automatically.


📦 Download FPDF Library

Download FPDF from:
👉 https://www.fpdf.org/en/download.php

Unzip and place the fpdf.php file inside a folder named fpdf/.