Convert Doc/Docx Files To PDF using PHP

27,329

Open Office and This Code Helps me :)

<?php
    set_time_limit(0);
    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){
    //echo $output_url;
    //Invoke the OpenOffice.org service manager
    $osm = new COM("com.sun.star.ServiceManager") or die ("Please be sure that OpenOffice.org is installed.\n");
    //Set the application to remain hidden to avoid flashing the document onscreen
    $args = array(MakePropertyValue("Hidden",true,$osm));
    //Launch the desktop
    $oDesktop = $osm->createInstance("com.sun.star.frame.Desktop");
    //Load the .doc file, and pass in the "Hidden" property from above
    $oWriterDoc = $oDesktop->loadComponentFromURL($doc_url,"_blank", 0, $args);
    //Set up the arguments for the PDF output
    $export_args = array(MakePropertyValue("FilterName","writer_pdf_Export",$osm));
    //print_r($export_args);
    //Write out the PDF
    $oWriterDoc->storeToURL($output_url,$export_args);
    $oWriterDoc->close(true);
    }
    $output_dir = "C:/wamp/www/vineesh/";
    $doc_file = "C:/wamp/www/vineesh/vineesh.docx";
    $pdf_file = "vineesh.pdf";
    $output_file = $output_dir . $pdf_file;
    $doc_file = "file:///" . $doc_file;
    $output_file = "file:///" . $output_file;
    word2pdf($doc_file,$output_file);
    ?>
Share:
27,329
V A S
Author by

V A S

Software Developer: LAMP Stack, React JS, Laravel, JavaScript, JIRA, Confluence

Updated on August 24, 2020

Comments

  • V A S
    V A S almost 4 years

    I am looking for a PHP code or PHP Library to convert microsoft doc/docx files to PDF. I am not familiar with Zend. Please help me to convert my word files to PDF successfully.

  • Deenadhayalan Manoharan
    Deenadhayalan Manoharan over 9 years
    But i have error this code "Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `com.sun.star.ServiceManager': Invalid syntax ' in C:\xampp\htdocs\learn\word.php:11 Stack trace: #0 C:\xampp\htdocs\learn\word.php(11): com->com('com.sun.star.Se...') #1 C:\xampp\htdocs\learn\word.php(30): word2pdf('file:///C:/xamp...', 'file:///C:/xamp...') #2 {main} thrown in C:\xampp\htdocs\learn\word.php on line 11
  • V A S
    V A S over 9 years
    Please be sure that OpenOffice.org is installed. install open office in your pc or server.
  • Deenadhayalan Manoharan
    Deenadhayalan Manoharan over 9 years
    How can i install OpenOffice in my xampp server
  • Flozza
    Flozza over 7 years
    I guess this solution is only for windows system ?
  • Nitin
    Nitin almost 7 years
    I guess COM is only supported in windows you can check this php.net/manual/en/com.requirements.php what about ubuntu system