SoFunction
Updated on 2025-03-08

PHP calls OpenOffice to implement word to PDF

Recently, I have been studying to convert PHP word documents to PDFs, and have also searched for a lot of similar information online, most of which are converted through OpenOffice.

The core code is as follows:

function MakePropertyValue($name,$value,$osm){ 
  $oStruct = $osm->Bridge_GetStruct(""); 
  $oStruct->Name = $name; 
  $oStruct->Value = $value; 
  return $oStruct; 
}


function word2pdf($doc_url, $output_url){ 
  $osm = new COM("") or die ("Please be sure that  is "); 
  $args = array(MakePropertyValue("Hidden",true,$osm)); 
  $oDesktop = $osm->createInstance(""); 
  $oWriterDoc = $oDesktop->loadComponentFromURL($doc_url,"_blank", 0, $args);
  $export_args = array(MakePropertyValue("FilterName","writer_pdf_Export",$osm));
  $oWriterDoc->storeToURL($output_url,$export_args); 
  $oWriterDoc->close(true); 
}


$doc_file=dirname(__FILE__)."/"; //Source files, DOC or WPS are OK$output_file=dirname(__FILE__)."/"; //The file name of the PDF to be transferred$doc_file = "file:///" . $doc_file;
$output_file = "file:///" . $output_file;
$document->word2pdf($doc_file,$output_file);

Using the above code, it has been reported errors

( ! ) Fatal error: Uncaught exception 'com_exception' with message '<b>Source:</b> [automation bridge] <br/><b>Description:</b> : ' in I:\phpStudy\WWW\DocPreview\ on line 27

( ! ) com_exception: <b>Source:</b> [automation bridge] <br/><b>Description:</b> : in I:\phpStudy\WWW\DocPreview\ on line 27

Finally, I found that it was a problem with the outgoing path: through debugging, the outgoing path of the above code is $output_file file:///I:\phpStudy\WWW\DocPreview\.

However, the path required in the storeToURL method is as follows: file:///I:/phpStudy/WWW/DocPreview/.

So just replace "\" of $output_file with "/"

$doc_file=dirname(__FILE__)."/"; //Source files, DOC or WPS are OK$output_file=dirname(__FILE__)."/"; //The file name of the PDF to be transferred$output_file=str_replace("\\","/",$output_file);
$doc_file = "file:///" . $doc_file;
$output_file = "file:///" . $output_file;
$document-&gt;word2pdf($doc_file,$output_file);

The above method of calling OpenOffice to implement word to PDF in PHP is all the content I share with you. I hope you can give you a reference and I hope you can support me more.