How to convert Word document into PDF using PHPWord

Kiran picture Kiran · Dec 20, 2017 · Viewed 18.2k times · Source

I am creating a Microsoft Word report using PHPWord. I basically start with a template and populate the fields and save it as a word report.

I would like to convert this report into a pdf file. I tried loading the generated doc file through PHPWord. However, when I save the pdf file, the formatting is all lost.

Here is the code I am using :

       require_once DOC_ROOT . '/vendor/phpoffice/phpword/bootstrap.php';

$path_to_tcpdf = DOC_ROOT . '/includes/plugins/TCPDF/'; // C:\xampp\htdocs\clients\corporate\includes\plugins\TCPDF
\PhpOffice\PhpWord\Settings::setPdfRendererPath($path_to_tcpdf);
\PhpOffice\PhpWord\Settings::setPdfRendererName('TCPDF');

$report_file_doc = DOC_ROOT . '/reports/business_report_U72900GJ2002PTC040573_68628.docx';
$report_file_pdf = DOC_ROOT . '/reports/business_report_U72900GJ2002PTC040573_68628.pdf';



$phpWord = \PhpOffice\PhpWord\IOFactory::load($report_file_doc); 
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord , 'PDF');

$xmlWriter->save($report_file_pdf);  

Any idea what could be missing ?

Thanks

Answer

Anton Pelykh picture Anton Pelykh · Jan 29, 2018

For PHPWord v0.14

Here's an example for TCPDF renderer (deprecared in v0.13):

// Require composer autoloder.
require __DIR__.'/vendor/autoload.php';

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Settings;

// Set PDF renderer.
// Make sure you have `tecnickcom/tcpdf` in your composer dependencies.
Settings::setPdfRendererName(Settings::PDF_RENDERER_TCPDF);
// Path to directory with tcpdf.php file.
// Rigth now `TCPDF` writer is depreacted. Consider to use `DomPDF` or `MPDF` instead.
Settings::setPdfRendererPath('vendor/tecnickcom/tcpdf');

$phpWord = IOFactory::load('document.docx', 'Word2007');
$phpWord->save('document.pdf', 'PDF');

Here's an example for DomPDF renderer:

// Require composer autoloder.
require __DIR__.'/vendor/autoload.php';

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Settings;

// Make sure you have `dompdf/dompdf` in your composer dependencies.
Settings::setPdfRendererName(Settings::PDF_RENDERER_DOMPDF);
// Any writable directory here. It will be ignored.
Settings::setPdfRendererPath('.');

$phpWord = IOFactory::load('document.docx', 'Word2007');
$phpWord->save('document.pdf', 'PDF');