Guvanch Hojamov
Guvanch Hojamov

Reputation: 346

How to use Mpdf library with PHPword. How can I generate .docx file to .pdf file

I have a problem. When I try to generate the word.docx file to pdfFile.pdf file on Laravel (PHP), using the library mPDF I got this error:

PDF rendering library or library path has not been defined.

I can't found the solution. Help me please. Thank you in advance.

My code in PHP controller file:

public function wordToPdf(){
    $domPdfPath = base_path('vendor/mpdf/mpdf');
    \PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
    \PhpOffice\PhpWord\Settings::setPdfRendererName('mPDF');
    
    //Load word file
    $Content = \PhpOffice\PhpWord\IOFactory::load(public_path( '/uploads/word/no12.docx'));
    
    //Save it into PDF
    $PDFWriter = \PhpOffice\PhpWord\IOFactory::createWriter($Content,'PDF');
    $PDFWriter->save(public_path( '/uploads/word/result3.pdf'));
    return $PDFWriter;
}

Help me please if anyone know it..?

Upvotes: 1

Views: 3984

Answers (1)

Saud
Saud

Reputation: 878

I had the same issue but with different library, It was because, the Laravel could not find the base path of your PDF rendering library and it is pretty clear in your error.

All you have to do is define a path to your domPDF. A better approach would be to define a constant and then access it. Here's how you do it:

  1. Create a file in your config folder by any name you want, constants.php would be a good practice since you're defining constants for your app.
  2. Define a constant in that file 'your_var_name' => realpath(__DIR__),.
  3. Run these commands in your cmd: php artisan config:cache and php artisan cache:clear to clear and cache the latest configs.
  4. Now in your controller setup the following settings:

Code:

// access your constant using laravel's helper config();
$domPdfPath = realpath(config('constant.your_var_name').'/../vendor/dompdf/dompdf');

Settings::setPdfRendererPath($domPdfPath);

Settings::setPdfRendererName('DomPDF');

Upvotes: 1

Related Questions