Word to PDF Converter in PHP (Word2PDF)

Jun
06
2005

Lots of people want to convert Word docs into PDF's (Word2PDF). Here's a Windows PHP converter of Word documents to PDF using OpenOffice via a COM wrapper of the OpenOffice API's. It's a lot of description for something fairly simple.

<?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){
//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));
//Write out the PDF
$oWriterDoc->storeToURL($output_url,$export_args);
$oWriterDoc->close(true);
}
$output_dir = "C:/dev/openofficeintegration/docconverter/";
$doc_file = "C:/dev/openofficeintegration/docconverter/DpmR5Reqv1.20.doc";
$pdf_file = "DpmR5Reqv1.20.pdf";
$output_file = $output_dir . $pdf_file;
$doc_file = "file:///" . $doc_file;
$output_file = "file:///" . $output_file;
word2pdf($doc_file,$output_file);
?>

 

Comments on this post

Feedback is always welcome. Read some from other folks or leave your own below. Just keep things civil and remember that what you post lives on in public. Forever.

Thanks,
J

62 Responses to “Word to PDF Converter in PHP (Word2PDF)”

  1. J Wynia » Turn Word docs into PDF using PHP Says:

    [...] one of the more useful conversions and takes very little code. A sample script is up at: Article Link: Word to PDF Conversion using PHP/COM/OpenOffice C [...]

  2. how to use this in linux Says:

    I am working on PHP using linux system.
    Thanks

  3. Martin Dean Says:

    Hi,

    I have installed OpenOffice.org 2.0. I try a test of this code and I get the following error.

    "Unable to obtain IDispatch interface for CLSID {82154420-0FBF-11D4-8313-005004526AB4}: "

    I have sniffed around the web, but other instances of this problem I find seem to relate to IIS. However, I use Apache not IIS….any ideas.

    Thanks

    Martin
    Melbourne, Australia

  4. Bekki Says:

    You dont need the code with Openoffice… You just need to press the small icon with the PDF logo on it. :)

  5. J Wynia Says:

    If you're only changing 1 document or are sitting at the computer, sure. However, many of these conversions I do are actually uploaded files or a batch of 300 that need to be done and there's no way I'm clicking that button 300 times.

    Much of this kind of coding is about eliminating repetitive tasks. Those tasks can be done one at a time with little effort, but pile up quickly when you have more than a few to do.

  6. bala Says:

    hi,
    i try yhis code but get an error for inittialization what to do?i sure i install openoffice2.1 in my system

    $osm = new COM("com.sun.star.ServiceManager");

    error:

    Unable to obtain IDispatch interface for CLSID {82154420-0FBF-11D4-8313-005004526AB4}: Server execution failed in

  7. J Wynia Says:

    I believe most of the errors were due to how Wordpress modified the code to change normal quotes to smart quotes. I've changed the code, so if you had a problem in the past, give it another try.

  8. ss Says:

    Can someone provide Unix version

  9. ss Says:

    Can someone provide Unix version. Would preferr to use PHP

  10. balri Says:

    Yeah, a unix/linux version would be most helpful

  11. J Wynia Says:

    Sorry, guys, until someone writes an OpenOffice binding for PHP, I don't know of any way nearly this easy. At the moment, the only gateway to OpenOffice from PHP that I know of is COM.

  12. karthik Says:

    Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `com.sun.star.ServiceManager': Invalid syntax ' in D:\wamp\www\word_editor\word2pdf.php:11 Stack trace: #0 D:\wamp\www\word_editor\word2pdf.php(11): com->com('com.sun.star.Se…') #1 D:\wamp\www\word_editor\word2pdf.php(33): word2pdf() #2 {main} thrown in D:\wamp\www\word_editor\word2pdf.php on line 11

  13. karthik Says:

    I got the following Fata error. What i will do to clear the error?

    Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `com.sun.star.ServiceManager': Invalid syntax ' in D:\wamp\www\word_editor\word2pdf.php:11 Stack trace: #0 D:\wamp\www\word_editor\word2pdf.php(11): com->com('com.sun.star.Se…') #1 D:\wamp\www\word_editor\word2pdf.php(33): word2pdf() #2 {main} thrown in D:\wamp\www\word_editor\word2pdf.php on line 11

  14. J Wynia Says:

    The first quote around the COM object isn't a regular quote, it's a "smart" quote. Type in the code for that line in your text editor manually and it should work.

  15. Mino Says:

    Hi there.

    If you are looking for a solution under linux.

    see http://j.crecy.free.fr/index.php/2006/03/01/3-php_word_to_pdf

    OK it's in french and I just putted it tonight and I didn't take care about the presentation and ….
    … and it's "quick and dirty" (the code as the presentation)

    But It Works.

  16. uttam majumder Says:

    Please send me details why i face this types of error

  17. mino Says:

    —-
    J Wynia Says:
    February 19th, 2006 at 6:36 pm
    Sorry, guys, until someone writes an OpenOffice binding for PHP, I don’t know of any way nearly this easy. At the moment, the only gateway to OpenOffice from PHP that I know of is COM.
    —-

    Maybe we could have direct access using java classes as we can now compile php5 to use java classes … Not yet tested but i've added it in my toto list…

    I've got a client that is intersted by the dirty solution that i presented using python uno binding. It's an occasion to work on a more reliable solution like using java classes in native php code …

    I'll tell you about the result of my investigation…

    If someone already did it could spend me time.

  18. Arun Says:

    Hi,

    I've used above code for conversion process. i've installed open office 1.1.4 in my system.

    but, i got this error :-

    "Warning: (null)(): Invalid ProgID, GUID string, or Moniker: Invalid syntax in c:\inetpub\wwwroot\ave\wordpdf.php on line 11
    PHP has encountered an Access Violation at 00D3A8A8 "

    Any one have an idea to rectify this? i can't understand watz the actual error?

    Regards,
    Arun.M.D

  19. Alex Says:

    very useful , thank you.

    Alex

  20. iko Says:

    Hi,
    i want to convert word2pdf under Sun Solaris System. System admin didnt allow to setup Openoffice on system. Is there any way to convert word2pdf under Sun Solaris without setup openoffice?

  21. Diego Says:

    hi, more general…. is there a way to use the API (copy the corresponding w32/linux/etc version) without installing OO.org in a server?
    thanks!

  22. J Wynia Says:

    On windows, I suppose it's possible to just install and register all of the appropriate COM object DLL's and take care of dependencies, etc. I just don't know where that would be worth it in a scenario where just putting oo.org on wouldn't work.

    Regardless, in all OpenOffice access has to go through a connector of some sort. The only one I've used for PHP is the Windows COM layer. The Java layer might give access in PHP, but I haven't looked at it.

  23. Jonathan W. Vicente Says:

    Hi,

    It's possible to install only the API com.sun.star.ServiceManager on a linux server? If so how can I do that.

  24. J Wynia Says:

    No, not in any way that I know of.

  25. Diego Says:

    I created a PHP file with the code above and installed the latest OO.org (2.something)
    (here it shows a strange ` but as the scripts shows the call is $osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue");)
    Is there something else I need to configure?? in php.ini? I gave the file and folder full permissoons…

    Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `com.sun.star.ServiceManager': Access is denied. ' in c:\Inetpub\wwwroot\pdf\word2pdf.php:13 Stack trace: #0 c:\Inetpub\wwwroot\pdf\word2pdf.php(13): com->com('com.sun.star.Se…') #1 c:\Inetpub\wwwroot\pdf\word2pdf.php(33): word2pdf('file:///C:/doc_…', 'file:///C:/doc_…') #2 {main} thrown in c:\Inetpub\wwwroot\pdf\word2pdf.php on line 13

  26. Munira Says:

    Hi
    I am trying to convert doc file with your code.but i am getting this error: 'The specified CGI application misbehaved by not returning a complete set of HTTP headers.' whats wrong? can u help me please.

  27. Vijay Dubey Says:

    Hi,
    I have convert word document in my c# windows application. Can any one guide me that how do i convert word document into PDF in my c# project.

  28. students Says:

    can any one me tell some way of converting a pdf to a word file(.doc) or atleast any text format by using php

  29. Aron Says:

    how can I do this on a shared linix account?

  30. Pavan ahuja Says:

    Can you give the solution for how I read pdf file data and convert it in to text format using php on the fly? I really thank full if you give any idia regarding this.

  31. Pat S Says:

    This may sound crazy, but I have Adobe Acrobat Pro 8 (had 7 previously) and the program installs a pdf writer that works with MS word. Open your doc in word, click the acrobat icon and viola.

    Not sure why one wouldn't just go that route? Of course, I have acrobat pro because I use creative suite cs2 and it comes with it…

    don't know if they make a linux based one or not. Don't even know what php is. Sorry, i'm not so "in the loop these days." i was here for a different reason and caught this. That's all.

  32. Fabio Says:

    Hi i want to use a com class to convert files by the PDF4free how do i know the classID and the methods to use? i looked everywhere but didn't find any answer, thanks

  33. J Wynia Says:

    If you've got Visual Studio (or one of the free Visual C# or Visual VB.NET Express Editions), you can dig through pretty much any COM or .NET object on your system.

  34. Fabio Says:

    Hi J thanks fot the answer, i don't have VB and i did'nt intend to use it, but i mannage to do what i wanted to do with your script
    Thank you very much, i read the API documentantio on the Open Office Org and read the methods and which things they needed to,

    Thank you very much J
    ^^

  35. Diego Says:

    Hi. I used the code but no luck… I have OO.org 2.02 (or similar) version installed. What/how do I manage to tell php to use the API from oo.org? (i'm trying with winodows xp and PHP 4.
    Thanks
    Diego

  36. fabio Says:

    Hey diego i had almost the same configuration as you are you changing the paths of the file?
    Make a test with a simple com task, if that works with you. get a read at the http://api.openoffice.org/docs/DevelopersGuide/DevelopersGuide.xhtml

    it is the HTML version of the developer's guide, see the name of the api's you wann use, use them as a COM object, see the methods and what they ask for, it probably will make things work,
    If even so it doesn't well…them i got no clue hehe

  37. Fabio Says:

    Hey j, i thought i had all unde my control, but i was only testting trough the debug fom my ide, whem i try to test it in the localhost iget

    Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `com.sun.star.ServiceManager': Falha na execução do servidor '(!ERROR IN THE SERVER EXECUTION!) in C:(!path!) Stack trace: #0(!PATH!): com->com('com.sun.star.Se…') #1 (!PATH!)('file:///C:/Docu…', 'file:///C:/Docu…') #2 {main} thrown in (!PATH!) on line 11 (!WHEM THE COM IS CREADE!)
    the (!…!) are comments or substitutions
    thank you j

  38. J Wynia Says:

    I've seen issues like that crop up when trying to run COM object scripts via the web server. What web server are you using?

  39. Fabio Says:

    Hi J so i'm testing it locally with wamp 5, i saw in the admnistrative systems in the event viewer ,i got a dcom error ,
    the error is the 10010 "The server{82154420-0FBF-11D4-8313-005004526AB4} did not register with DCOM within the required timeout.
    Since that {82154420-0FBF-11D4-8313-005004526AB4} id the ClsID of the openOffice and in the debug of my IDE i can make the program works, i guess that it is something with permissions or something like that, whit permissions did you gave to use your Word2PDF? or whit more changes did you had to make to get this thing works?
    Thanks as always J you are very nice in responding the e-mails of the noobies who seek you ^^

    PS: You can convert anything that openoffice convert with your program not just word

  40. yokel Says:

    I got this error:

    Warning: (null)(): Unable to obtain IDispatch interface for CLSID {82154420-0FBF-11D4-8313-005004526AB4}: Server execution failed in D:\equiptor\application\general\gn_general.inc on line 1257
    Please be sure that OpenOffice.org is installed.

    My platform is Apache 2.0.55, PHP 4.3.4 on WinXP Professional with OpenOffice 2.0. Please advice how to overcome this error. I have no idea at all about this error. Thanks

  41. kumar chetan Says:

    Why write a script when you have
    a) OO
    b) Windows
    c) FPDF (http://www.fpdf.org/)
    d) ezpdf.class.php
    There are some issues which I am trying to solve and was doing googling and landed at your page.
    ch33r5

  42. J Wynia Says:

    1. Because this script, with only one modified can export Word to *any* format that OpenOffice supports.
    2. With only a couple of *other* changes, it will translate between any 2 formats OpenOffice supports.
    3. It serves as an example of how to integrate COM objects into PHP, something which isn't shown in tutorials very often.
    4. Because I can.

  43. kumar chetan Says:

    I agree with u on last point :P
    In fact on all and ur point 3 is really good, its rare to find any good tuto that helps u do COM using PHP. The problem I am facing is simple to state, "Convert doc file to PDF using PHP". But
    a) the server is linux
    b) hosting is shared
    Hence no real solution till now. Can U help me?

  44. fabio Says:

    Hi kummar i have some "solutions" for you , you can either use JOO:
    http://jooreports.sourceforge.net/?q=jooconverter
    you can write an openoffice macro like this from danny:
    http://www.oooforum.org/forum/viewtopic.phtml?t=3772&postdays=0&postorder=asc&start=105

    the macro is in here:
    http://kosh.datateamsys.com/~danny/OOo/Examples/Conversions/

    the first one
    and call it by php shell.

    But look out , this makepropertyvalue function in my fedora is giving a lot of headache, but i guess it works perfectly in any fedora highert than 5 and any debian.
    good luck

  45. Russell Pruitt Says:

    Hey J,

    Man I am trying to get this script going on a Windows XP machine using XAMPP. Its apache2, php 5.2, and the server gives a 'com_exeception' with 'Server Execution Failed'. Seeing as how when I googled the com.sun.star.ServiceManager I saw responses on an 'Access Denied' error I am assuming I have made all the appropriate changes to the security for the Open Office 1.1 Text component object. Nevertheless I continue to still receive these errors. Any help would be much appreciated. Also I am using the most current version of OO will this make a difference?

  46. Russell Pruitt Says:

    It appears that along with the DCOM security you also need to allow use of the OOo software. Meaning enable access to the entire OOo software folder, I recommend setting an identity to a user you know and then give that user access to the correct folders. Also if anyone could please tell me how to close the objects after they have been called so that I don't have OOo eating up 50mb of RAM. =D

  47. Mahesh Says:

    How can i get Propery information of a word file, like No of Lines, No of words, No of space etc

  48. gAmringer Says:

    I am trying to change the page setup (paper size and margins), but I have no idea at all how COMs work. Can you help me with that ?

  49. sudhir Says:

    $osm = new COM("com.sun.star.ServiceManager") or die ("Please be sure that OpenOffice.org is installed.\n");

    i use this code but it will give Error:E_WARNING (null)():Invalid ProgID, GUID string, or Moniker : Invalid syntax.

  50. TriniOne Says:

    Hi all:
    After spending many hours searching I found this new and current website.

    Docvert - MS Word to Open Standards

    Here is the link:
    http://holloway.co.nz/docvert/

    Regards,
    TriniOne

  51. rajan Says:

    i wanna to ask
    i have make pdf file using php the data from database

    and wanna link in output data coming from database

    can i use link in pdf for open another pdf file

  52. I. Alvarado Says:

    Hey all,

    I got the same error as many people before:
    Uncaught exception 'com_exception' with message 'Failed to create COM object `com.sun.star.ServiceManager': Server execution failed,

    I did as J told, "Type in the code for that line in your text editor manually and it should work." but no luck… I checked the Windows registry:

    HKEY_LOCAL_MACHINE\SOFTWARE\Classes\
    CLSID\{82154420-0FBF-11d4-8313-005004526AB4}

    And the OpenOffice.org Service Manager (Ver 1.0) seems to be installed. I'm running the script with wamp5 1.7.2, does someone knows if need to configure wamp5 ?

  53. Russell Pruitt Says:

    You have to give permission to the component.. its a real pain but that should fix it. Components can be found in the Administrative Tools.

  54. Martin Korych Says:

    RE: russell pruit

    I do appreciate your suggestion but would you mind pointing me the right direction in Vista please?

    Thank you,
    Martin

  55. vinod Says:

    Hello Dear,

    All friends have same problem. But no one is able to give the answer. what is the reason for this. Anyone will say about to configure the open office api with php.

  56. Ben Says:

    Hi All,

    I just though I would let you know how I got this script to work using a remote server. My problem was that the COM settings did not allow remote users access to open office.

    To change this access the server and follow these steps:
    1. Run -> dcomcnfg
    2. Component Services -> DCOM Config
    3. OpenOffice.org 1.1 Text Document -> Properties -> Identity (tab)
    4. Now enter a specific user that has permission (i.e. your admin username and password)

    I was running IIS on windows server.

    Also, if you wish to check everything is running you can call your script directly using a .bat file. just enter the line:
    @c:\php\php.exe -q C:\Inetpub\wwwroot\pdf.php

    Hopefully this helps someone else.

    Ben

  57. armata Says:

    hello,

    i try to use this script on wamp server, but i have an error:

    Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `com.sun.star.ServiceManager': Invalid syntax ' in…

    i try to use curly quote befor com.sun… and regular quote after whith no effect, can anyone help me?
    (i'm using pspad editor, did it cause probleme?)
    (2nd Exuse my english, i'm french ;-)

  58. santy Says:

    hallo,

    I am trying this script to convert to ,doc to .pdf file but there is error like "com" object is not found and other related to "$osm = new COM("com.sun.star.ServiceManager") " this line
    I am instal openoffice.org

    for proper run this script what a have to do
    can I java+php integarte to run "com.sun.star.ServiceManager"???

    please suggest me to get errorless output as soon as possible.

    thank u

  59. Antonis Says:

    Hi,

    I tried this script and works with a simple doc file. BUT Apache crashes. WinXP, Apache 1.3 with php4 or php5 OR Apache2 with php5. No useful error logs from apache…

  60. blight Says:

    The problem with COM is that you can't use it on linux. Other PDF generation tools require special php extensions.

    Here is some sample code from zedwood.com that demonstrates how to
    generate a simple pdf in php.

  61. Adeel Says:

    hi,i tried this script this script work well locally but online show error
    anybody help me
    Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `com.sun.star.ServiceManager': Server execution failed ' in D:\websites\editor@silentscribes.com\silentscribes.com\wwwroot\doc2pdf.php:11 Stack trace: #0 D:\websites\editor@silentscribes.com\silentscribes.com\wwwroot\doc2pdf.php(11): com->com('com.sun.star.Se…') #1 D:\websites\editor@silentscribes.com\silentscribes.com\wwwroot\doc2pdf.php(30): word2pdf('file:///d:/webs…', 'file:///d:/webs…') #2 {main} thrown in D:\websites\editor@silentscribes.com\silentscribes.com\wwwroot\doc2pdf.php on line 11

  62. Jargon Says:

    Is there any good web hosting providers where this script will work perfectly. At our current server we are constantly getting access is denied error. And support is unable to solve this problem.

  63. Leo Bonnafé Says:

    A relatively new project called phpLiveDocx does exactly what you want. It is written in PHP can can convert between DOC and PDF (in addition to a number of other formats). For details, see: http://www.phplivedocx.org.

Leave Your Own Comment

By submitting a comment, you agree to license it under the terms of the Creative Commons Attribution license.

People who post comments get the added benefit of visiting the site without advertising.

© 2003-2009 J Wynia. All original content is licensed under the terms of the Creative Commons Attribution license unless otherwise noted. Content from other sources is licensed under its original terms.