PHP calls OpenOffice to realize the method of word to PDF

  • 2021-08-10 07:30:01
  • OfStack

Recently, I have been studying the conversion of PHP word documents to PDF, and I have searched many similar materials on the Internet, most of which are converted through OpenOffice.

The core code is as follows:


function MakePropertyValue($name,$value,$osm){ 
  $oStruct = $osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue"); 
  $oStruct->Name = $name; 
  $oStruct->Value = $value; 
  return $oStruct; 
}


function word2pdf($doc_url, $output_url){ 
  $osm = new COM("com.sun.star.ServiceManager") or die ("Please be sure that OpenOffice.org is installed.n"); 
  $args = array(MakePropertyValue("Hidden",true,$osm)); 
  $oDesktop = $osm->createInstance("com.sun.star.frame.Desktop"); 
  $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__)."/11.doc"; // Source files, DOC Or WPS All right 
$output_file=dirname(__FILE__)."/11.pdf"; // Want to turn PDF File name of 
$doc_file = "file:///" . $doc_file;
$output_file = "file:///" . $output_file;
$document->word2pdf($doc_file,$output_file);

Use the above discovery code 1 to report errors directly

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

( ! ) com_exception: < b > Source: < /b > [automation bridge] < br/ > < b > Description: < /b > com.sun.star.task.ErrorCodeIOException: in I:\phpStudy\WWW\DocPreview\test2.php on line 27

Finally, it is found that the original turn-out path is the problem: through debugging, the turn-out path of the above code $output_file is file://I:\ phpStudy\ WWW\ DocPreview\ sdds. pdf.

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

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


$doc_file=dirname(__FILE__)."/11.doc"; // Source files, DOC Or WPS All right 
$output_file=dirname(__FILE__)."/11.pdf"; // Want to turn PDF File name of 
$output_file=str_replace("\\","/",$output_file);
$doc_file = "file:///" . $doc_file;
$output_file = "file:///" . $output_file;
$document->word2pdf($doc_file,$output_file);

Related articles: