In today’s digital world, converting image files like JPG to PDF format is a common requirement, especially for developers building document management systems, user portals, or online form upload tools. PHP, being a powerful server-side scripting language, allows us to automate this task easily using a free and open-source library called FPDF.
What is FPDF?
FPDF stands for Free PDF. It is a PHP class that allows you to generate PDF files with pure PHP, without requiring any external extension. It is simple, lightweight, and supports features like adding text, images, and graphics to a PDF document.
Why Convert JPG to PDF?
- Universal Format: PDF files are more universally accepted and consistent across devices compared to image formats.
- Multiple Pages: You can combine several images into a multi-page PDF.
- File Size: PDF files can be compressed better than high-resolution JPGs in some cases.
- Security: PDF supports password protection and watermarking for extra security.
PHP Code to Convert JPG to PDF
Here’s a simple script using the FPDF library:
require('fpdf.php');
$image = 'example.jpg';
$pdf_output = 'output.pdf';
list($width, $height) = getimagesize($image);
$width_mm = $width * 0.264583;
$height_mm = $height * 0.264583;
$pdf = new FPDF('P', 'mm', array($width_mm, $height_mm));
$pdf->AddPage();
$pdf->Image($image, 0, 0, $width_mm, $height_mm);
$pdf->Output('F', $pdf_output);
After running this script, your JPG image will be saved as a PDF file in the same folder.
Step-by-Step Guide
- Download the FPDF library from https://www.fpdf.org.
- Place the
fpdf.php
file in your working directory. - Use the PHP script above, replacing
example.jpg
with your image file. - Run the script and get your
output.pdf
file.
Bonus: Upload and Convert
You can also build a form where users upload a JPG and PHP automatically converts it into a downloadable PDF. This is ideal for e-KYC, ID upload, and document management systems.
Conclusion
With just a few lines of code and the help of the FPDF library, you can easily convert any JPG image into a PDF using PHP. It’s a useful feature for web apps, especially when working with scanned documents or official ID submissions. Try integrating it into your next PHP project and offer your users a more flexible and professional file handling experience!
0 Comments
Post a Comment