Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Christian-manganelli's avatar

How to convert Blob into PDF and make them downloadable

Hi guys, I am a beginner to Laravel 8 and also new to Laracasts, I have a table in my client DB that is storing some documents. They all are supposed to be PDF but they're stored as Blob in a Doc_file column. Other info I have are Column with the filename and the filetype and something about the strings of the docs.

I am echoing the documents on a page and put them inside an anchor tag with "download attribute" but Is not working. I think I need to convert it somehow from Blob to PDF and then retreive a kind of a path or something? I am a bit lost about that...can someone help me?

Thanks in advance!

0 likes
1 reply
LaryAI's avatar
Level 58

To convert a Blob into a PDF and make it downloadable in Laravel, you can follow these steps:

  1. Retrieve the Blob data from the database using the appropriate model and column.
  2. Create a new PDF file using a library like Dompdf or TCPDF.
  3. Save the Blob data into the PDF file.
  4. Generate a unique filename for the PDF file.
  5. Store the PDF file in a publicly accessible directory, such as the public/storage directory.
  6. Create a route in your Laravel application that will handle the download of the PDF file.
  7. In the route's controller method, retrieve the PDF file from the storage directory and return it as a downloadable response.

Here's an example implementation using the Dompdf library:

use Dompdf\Dompdf;
use Illuminate\Support\Facades\Storage;

// ...

public function downloadPdf($id)
{
    // Retrieve the Blob data from the database
    $document = Document::findOrFail($id);

    // Create a new Dompdf instance
    $dompdf = new Dompdf();

    // Load the Blob data into Dompdf
    $dompdf->loadHtml($document->doc_file);

    // Render the PDF
    $dompdf->render();

    // Generate a unique filename for the PDF file
    $filename = uniqid() . '.pdf';

    // Store the PDF file in the storage directory
    Storage::disk('public')->put($filename, $dompdf->output());

    // Return the PDF file as a downloadable response
    return response()->download(storage_path('app/public/' . $filename));
}

In this example, the downloadPdf method retrieves the Blob data from the doc_file column of the Document model. It then creates a new Dompdf instance, loads the Blob data into it, and renders the PDF. The rendered PDF is then stored in the public/storage directory using a unique filename. Finally, the method returns the PDF file as a downloadable response.

You will need to adjust the code according to your specific database structure and file storage configuration. Additionally, make sure to install the Dompdf library using Composer before using it in your Laravel application.

Please or to participate in this conversation.