Generating PDF from HTML in Laravel with Variable Replacement

47 Views Asked by At

I have the following Laravel controller:

<?php

namespace App\Http\Controllers\Administrador;

use PDF;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Blade;

use App\Http\Controllers\Controller;

use App\User;
use App\DocContrato;

class MantenedorContratosController extends Controller
{
    public function index()
    {
        return view('administrador.mantenedor_contratos.index');
    }

    public function pdf(Request $request)
    {
        $doc_contrato = DocContrato::find(1);

        $htmlContent = Blade::compileString($request->myeditorinstance, [
            'doc_contrato' => $doc_contrato,
        ]);

        $pdf = PDF::loadHTML($htmlContent);

        return $pdf->stream('document.pdf');
    }
}

The $request contains $htmlContent = $request->myeditorinstance;, which is the following HTML code:

<div>
<div id="titleconcurso">"{{ $doc_contrato->nombre_concurso }} {{ $doc_contrato->anio_concurso }}"</div>
</div>
<div id="textoinicio">
<div>Folio Proyecto:&nbsp; {{$doc_contrato->folio}}</div>
<div>Nombre del Proyecto: " {{$doc_contrato->nombre_proyecto}} "</div>
</div>

What I want to do is compile the HTML without using a Blade view file. I need to load this HTML content from a database and render it into a PDF file. However, the variables from the $doc_contrato do not appear to be reflected in the generated PDF.

My dependencies include Laravel, Barryvdh\DomPDF, and TinyMCE. How can I ensure that the $doc_contrato variable is properly replaced in the HTML content when generating the PDF?

0

There are 0 best solutions below