Change .jpeg to .pdf with php

0

I have a form where I can upload a file and rename that file, normally jpeg files are uploaded but I need to convert them to .pdf, would there be any way to make it easy with php?

I leave the code where you upload and rename the file

<?php 
    $target_path = "albaranes/";
    $tipo_archivo = $_FILES['uploadedfile']['type'];
    $tipo_archivo = explode("/", $tipo_archivo);
    $tipo_archivo= '.'.$tipo_archivo[1];
    $nombre_archivo= $_POST['albaran'].$tipo_archivo;
    $target_path = $target_path.$nombre_archivo;

     if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { 
        echo "<script type='text/javascript'>
			window.location='redireccionar.php';
			</script>";
    } 
     else{
        echo $target_path;
    }
?>
    
asked by Tefef 05.04.2018 в 10:36
source

2 answers

0

You can use the Imagick module to convert an image to the format you want. Once you have what you need you can do the following:

$img = new Imagick('path/to/image.jpg');
$img->setImageFormat('pdf');
$success = $img->writeImage('path/to/image.pdf');

O

$img = new Imagick();
$img->readImageBlob($imageBytes);
$img->setImageFormat('pdf');
$success = $img->writeImage('path/to/image.pdf');

Imagick Handbook

Source

    
answered by 05.04.2018 в 10:40
0

In fact yes, you can use Imagick to convert the image to the format you want, in your case to pdf.

<?php 
    //$target_path = $target_path.$nombre_archivo;
    // -- Puedes verificar que sea solo para las imagenes
    $extIMG = "/^(jpg|jpeg)$/i";
    if (!preg_match($extIMG, $tipo_archivo)) {
        $nombre_archivo = $_POST['albaran'].".pdf";
        //-- Lo puedes trabajar con la ruta temporal
        $pdf = new Imagick($_FILES['uploadedfile']['tmp_name']);
        $pdf->setImageFormat('pdf');
        if ($pdf->writeImage($target_path.$nombre_archivo)) {
            echo "<script type='text/javascript'>
                      window.location='redireccionar.php';
                  </script>";
        } else {
            echo $target_path.$nombre_archivo;
        }
    } else { //-- Continua como lo tenias anteriormente
        if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { 
            echo "<script type='text/javascript'>
                      window.location='redireccionar.php';
                  </script>";
        } else {
            echo $target_path.$nombre_archivo;
        }
    }
    
?>
    
answered by 05.04.2018 в 10:58