This repository provides a solution to convert images in JPG or PNG format into PDF documents using the FPDF library. It includes a core class for image conversion and practical usage examples.
- PHP 7.4 or higher.
- FPDF library.
- Composer-generated autoload library.
/
├── src/
│ ├── fpdf181/ # FPDF library folder
│ ├── uploads/ # Folder for uploading images and saving PDFs
│ ├── ImageConversor.php # Core class for converting images to PDF
│ ├── index.php # Script for handling image upload and conversion
│ ├── example.php # Direct usage example
├── composer.json # Composer dependency configuration
└── README.md # Project documentation
Location: src/ImageConversor.php
This class is responsible for converting images to PDF documents using FPDF.
private $fpdf
: Instance of theFPDF
class.
-
__construct()
Constructor that initializes theFPDF
instance. -
convertImgToPdf($imgRoute)
Converts an image to a PDF document with dimensions proportional to the image size in millimetres.
Parameters:string $imgRoute
: Path to the image file.
Exceptions:
- Throws an exception if the image does not exist.
-
advanceConvertImgToPdf($imgPath, $outPath)
An advanced conversion method that adjusts the PDF orientation (portrait or landscape) based on the image dimensions.
Parameters:string $imgPath
: Path to the input image.string $outPath
: Path to save the output PDF.
Exceptions:
- Throws an exception if the image does not exist.
Location: src/index.php
This script handles the image upload from an HTML form and converts it to PDF.
- Verifies if the request method is POST and if the image file is available.
- Creates an upload directory if it does not exist.
- Moves the uploaded image to the directory.
- Converts the image to PDF using
advanceConvertImgToPdf
. - Generates a download link for the converted PDF.
<form action="index.php" method="POST" enctype="multipart/form-data">
<label for="imageFile">Upload Image:</label>
<input type="file" name="imageFile" id="imageFile" accept="image/png, image/jpeg">
<button type="submit">Convert to PDF</button>
</form>
Location: src/example.php
A basic script that directly converts an image at the specified path to a PDF file.
- Defines the path of the image.
- Creates an instance of
ImageConversor
. - Converts the image using
convertImgToPdf
.
- Clone the repository:
git clone https://github.com/miusarname2/Img2Pdf
- Install dependencies:
composer install
- Start a PHP server:
php -S localhost:8000 -t src/
- Visit
http://localhost:8000/index.html
and upload an image.
-
"The image file does not exist"
Ensure that the file path is correct and the file is available. -
"Error uploading the file"
Make sure theuploads/
folder has write permissions.
This project is distributed under the MIT License. You are free to use, modify, and distribute it.
Este repositorio contiene una solución para convertir imágenes en formato JPG o PNG a documentos PDF utilizando la librería FPDF. Se incluye una clase principal para la conversión de imágenes y ejemplos de uso práctico.
- PHP 5.6 o superior.
- Librería FPDF.
/
├── src/
│ ├── fpdf181/ # Carpeta con la librería FPDF
│ ├── uploads/ # Carpeta para subir imágenes y guardar PDFs
│ ├── ImageConversor.php # Clase principal para la conversión de imágenes a PDF
│ ├── index.php # Script para manejo de la subida y conversión de imágenes
│ ├── example.php # Ejemplo directo de uso
├── composer.json # Configuración de dependencias de Composer
└── README.md # Documentación del proyecto
Ubicación: src/ImageConversor.php
Esta clase se encarga de convertir imágenes a documentos PDF utilizando FPDF.
private $fpdf
: Instancia de la claseFPDF
.
-
__construct()
Constructor que inicializa la instancia deFPDF
. -
convertImgToPdf($imgRoute)
Convierte una imagen a un documento PDF con dimensiones equivalentes a las de la imagen en milímetros.
Parámetros:string $imgRoute
: Ruta al archivo de imagen.
Excepciones:
- Lanza una excepción si la imagen no existe.
-
advanceConvertImgToPdf($imgPath, $outPath)
Conversión avanzada que ajusta la orientación del PDF (vertical u horizontal) según las dimensiones de la imagen.
Parámetros:string $imgPath
: Ruta de la imagen de entrada.string $outPath
: Ruta de salida para guardar el PDF.
Excepciones:
- Lanza una excepción si la imagen no existe.
Ubicación: src/index.php
Este script gestiona la carga de imágenes desde un formulario HTML y su conversión a PDF.
- Verifica si el método de solicitud es POST y si el archivo de imagen está disponible.
- Crea un directorio de subida si no existe.
- Mueve la imagen subida al directorio.
- Convierte la imagen a PDF utilizando
advanceConvertImgToPdf
. - Genera un enlace de descarga para el PDF convertido.
<form action="index.php" method="POST" enctype="multipart/form-data">
<label for="imageFile">Subir imagen:</label>
<input type="file" name="imageFile" id="imageFile" accept="image/png, image/jpeg">
<button type="submit">Convertir a PDF</button>
</form>
Ubicación: src/example.php
Un script básico que convierte directamente una imagen en la ruta especificada a un archivo PDF.
- Define la ruta de la imagen.
- Crea una instancia de
ImageConversor
. - Convierte la imagen con
convertImgToPdf
.
- Clona el repositorio:
git clone https://github.com/miusarname2/Img2Pdf
- Instala las dependencias:
composer install
- Inicia un servidor PHP:
php -S localhost:8000 -t src/
- Accede a
http://localhost:8000/index.html
y sube una imagen. - Modifica
example.php
para especificar la ruta de la imagen. - Ejecuta el script:
php src/example.php
-
"El archivo de imagen no existe"
Verifica que la ruta del archivo sea correcta y que el archivo esté disponible. -
"Error al subir el archivo"
Asegúrate de que la carpetauploads/
tiene permisos de escritura.
Este proyecto se distribuye bajo la Licencia MIT. Puedes usarlo, modificarlo y distribuirlo libremente.