Search code examples
phpmysqlblobimagick

How to Convert Image to PDF and store it as Blob using PHP and Imagick?


I am trying to convert an image into PDF File and then would like store the PDF file as a blob data in MySQL Database. I am using PHP and Imagick.

Problem: After convert the file to PDF that contains image and I stored it as BLOB in MYSQL DB. When I try to view it in PHP List Page or View Page. The PDF Shows blank white page.

Below is the code for the conversion.

$file = storage_path('test.jpg');
$image = new Imagick($file);

$image->setImageFormat('pdf');

$image->writeImage(storage_path('test.pdf'));

return "Done";

Code to Open PDF File and Store it as BLOB in medium blob field of the table.

  $fp = fopen($_SERVER['DOCUMENT_ROOT']."/location/files/uploads/imgtest.pdf ",'rb');
$fileContent = fread($fp,filesize($_SERVER['DOCUMENT_ROOT']."/location/files/uploads/imgtest.pdf "));
$fileContent = addslashes($fileContent);
//$fileContent = file_get_contents($path.$file.".pdf");
echo("filecontent: ".$fileContent);

fclose($fp);
$data = array();
$keyvalues = array();
$data["FileBlob"] = $file.".pdf";
$data["BlobPdf"] = $fileContent;
$data["FileName"] = "test.pdf";
$keyvalues['id'] = $id;
DB::Update("rawimage",$data,$keyvalues);

Code to Display the PDF File

    if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['id'])) {
    include __DIR__."/includes/DatabaseConnection.php";
    $id = htmlspecialchars($_GET['id']);
    $query = "SELECT `project_name`, `pdf_doc`
              FROM `project_pdf`
              WHERE `id` = :id;";
    $stmt = $pdo->prepare($query);
    $stmt->bindValue(':id', $id, PDO::PARAM_INT);
    $stmt->bindColumn(1, $project_name);
    $stmt->bindColumn(2, $pdf_doc, PDO::PARAM_LOB);
    if ($stmt->execute() === FALSE) {
        echo 'Could not display pdf';
    } else {
        $stmt->fetch(PDO::FETCH_BOUND);
        header("Content-type: application/pdf");  
        header('Content-disposition: inline; filename="'.$project_name.'.pdf"');
        header('Content-Transfer-Encoding: binary');
        header('Accept-Ranges: bytes');
        echo $pdf_doc; 
    }
} else {
    header('location: projects.php');
}

Solution

  • I modified the code and removed the link

    $fileContent = addslashes
    

    Now the file is being stored with the correct blob/binary data.