Making DomPDF as my pdf writer for phpWord

Bajongskie picture Bajongskie · Aug 29, 2014 · Viewed 18.1k times · Source

I used laravel for my app and the dompdf is found in:

../vendor/dompdf/dompdf

What I wanted to achieve is to convert my .docx file (Microsoft Word) to .pdf file. The docx file was generated by phpWord by loading the template file and replacing the values.

Here's the snippet:

 // Get the absolute path of the template file
 $wordTemplatePath = $this->getDocumentTemplatePath('resignation.docx');

 // Load the template file
  $document = $this->phpWord->loadTemplate($wordTemplatePath);

// This will be filled with data
 $wordData = []

.... Process to fill the data .....

// Replace value to actual word document
  $this->setTemplateValues($wordData, $document);


// Generate its filename
  $file = $this->generateFileName('Retirement-Certificate.docx', $id);

        // Fetch the absolute path to save the document
        $filepath = $this->getSavePath($file);

        // Save the word document
        $document->saveAs( $filepath );

After that, a .docx file will be generated. I wanted to make a PDF version of that as well. so I search and found this code snippet and added in my code:

             \PhpOffice\PhpWord\Settings::setPdfRendererPath('../vendor/dompdf/dompdf');
\PhpOffice\PhpWord\Settings::setPdfRendererName('DOMPDF');

//Load temp file
$phpWord = \PhpOffice\PhpWord\IOFactory::load($filepath); 

//Save it
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord , 'PDF');
$xmlWriter->save('result.pdf');  

But I got this error:

    {"error":
{"type":"PhpOffice\\PhpWord\\Exception\\Exception","message":"PDF rendering library or library path has not been defined.",
"file":"C:\\xampp\\htdocs\\vagrant\\vendor\\phpoffice\\phpword\\src\\PhpWord\\Writer\\PDF.php",
"line":49}}

How would I make DomPDF as my pdf writer for PHPWord? I can't find any other options so I ask here. I hope you can help me. Thanks!

Answer

Franz Holzinger picture Franz Holzinger · Sep 16, 2014

You must set it to the absolute path. Put this into your bootstrap.php file.

define('PHPWORD_BASE_DIR', realpath(__DIR__));

This is your call:

$domPdfPath = realpath(PHPWORD_BASE_DIR . '/../vendor/dompdf/dompdf');
\PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
\PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');

//Load temp file
$phpWord = \PhpOffice\PhpWord\IOFactory::load($filepath); 

//Save it
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord , 'PDF');
$xmlWriter->save('result.pdf');