如何使用 Dompdf 将 MySQL 数据库中的图像显示为 pdf

问题描述 投票:0回答:1
php laravel laravel-blade dompdf
1个回答
0
投票

要在 Laravel 中使用 DomPDF 以 PDF 形式显示 MySQL 数据库中的图像,您可以按照以下步骤操作:

确保您已安装所需的软件包:

DomPDF:作曲家需要 barryvdh/laravel-dompdf Laravel Collective HTML 包:composer require laravelcollective/html 确保您的数据库表包含用于存储图像数据的列。您可以使用 BLOB(二进制大对象)数据类型来存储图像。

在你的 Laravel Blade 视图(例如,certificate.blade.php)中,你可以使用 Laravel Collective HTML 包的 image 方法来显示图像。

这是您的证书控制器的更新代码:

namespace App\Http\Controllers;

use App\Models\Certificate;
use App\Models\Term;
use Illuminate\Http\Request;
use PDF;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class CertificateController extends Controller
{
    public function generateCertificate($termId)
    {
        // Fetch the term and relevant data
        $term = Term::find($termId);

        // Check if the term and necessary data are available

        // Get the authenticated user's name
        $userName = Auth::user()->name;
        $userLastName = Auth::user()->last_name;

        // Fetch the certificate data, including the logo
        $certificate = Certificate::first();

        // Prepare data for the certificate template
        $data = [
            'username' => $userName,
            'userlastname' => $userLastName,
            'course' => $term->course->title,
            'term' => $term->title,
            'date' => $term->finish_date,
            'logo' => Storage::disk('public')->url($certificate->logo), // Use the Storage facade to get the URL
            'position_1' => $certificate->position_1,
            'position_2' => $certificate->position_2,
            'name_1' => $certificate->name_1,
            'name_2' => $certificate->name_2,
        ];

        // Load the certificate template HTML
        $html = view('certificate.certificate', $data)->render();

        // Generate the PDF from the HTML
        $pdf = PDF::loadHTML($html);

        // Set the paper size to certificate size (e.g., A4) and landscape orientation
        $pdf->setPaper('Letter', 'landscape');

        // Set the file name for the PDF
        $fileName = 'certificate_' . $term->id . '.pdf';

        // Optionally, you can store the PDF on the server or force download
        // Example: $pdf->save(storage_path('certificates/' . $fileName));
        // Example: return $pdf->download($fileName);

        // Display the PDF in the browser
        return $pdf->stream($fileName);
    }

    // Method to handle the form submission
    public function index()
    {
        $certificate = Certificate::first(); // Retrieve a single certificate
        return view('contents.admin.badges.index', compact('certificate'));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.