Search code examples
pdfdocxdompdfphpword

Converting docx to pdf with phpword


I want to convert a docx file to pdf using phpword

my code looks like this:

$FilePath = APPPATH."media/Documentos/Facturas/Factura ".$FacturaId.".docx";
$FilePathPdf = APPPATH."media/Documentos/Facturas/Factura ".$FacturaId.".pdf";

//DOCX TO PDF
require_once APPPATH.'third_party/phpword/bootstrap.php';

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

$phpWord = new \PhpOffice\PhpWord\PhpWord();

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

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

But i generate an empty pdf file: LINK TO FILE

Paths are correct and .docx have content

I try with tcpdf render:

$rendererLibraryPath = PHPWORD_BASE_DIR . '/vendor/tecnickcom/tcpdf';
\PhpOffice\PhpWord\Settings::setPdfRendererPath($rendererLibraryPath);
\PhpOffice\PhpWord\Settings::setPdfRendererName('TCPDF');

and my pdf file have 2 pages without content: LINK TO 2ND FILE


Solution

  • Finally i found a free alternative solution installing libreoffice:

    $FilePath = APPPATH."media/Documentos/Facturas/Factura ".$FacturaId.".docx";
    $FilePathPdf = APPPATH."media/Documentos/Facturas/Factura ".$FacturaId.".pdf";
    
    require_once APPPATH.'third_party/phpword/bootstrap.php';
    $template = new \PhpOffice\PhpWord\TemplateProcessor(APPPATH.'media/Plantillas/Factura/Factura.docx');
    
    foreach($data as $key => $value){
        $template->setValue($key, $value);
    }
    
    $template->saveAs($FilePath);
    
    shell_exec($this->CI->config->item('libreoffice_exec')." --headless --convert-to pdf --outdir \"".$Path."\" \"$FilePath\"");
    

    Calling soffice.exe CLI with this parameters:

    soffice.exe --headless --convert-to pdf --outdir "C:/media/Documentos/Facturas/pdf" "C:/media/Documentos/Facturas/Factura1.docx";