OpenOffice.org Forum at OOoForum.orgThe OpenOffice.org Forum
 
 [Home]   [FAQ]   [Search]   [Memberlist]   [Usergroups]   [Register
 [Profile]   [Log in to check your private messages]   [Log in

Working Example: COM with PHP (Writer + TextFields...)

 
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Macros and API
View previous topic :: View next topic  
Author Message
Terminar
General User
General User


Joined: 23 Oct 2003
Posts: 10

PostPosted: Fri Oct 24, 2003 4:12 am    Post subject: Working Example: COM with PHP (Writer + TextFields...) Reply with quote

Hi All,

since one week, i'm dealing with php, c++ and openoffice. Many articles in this forum were very helpful, but there was no fully working example.
I needed to do a php prototype for dealing with textfields and the swriter and here it is, thanks for the articles!

This example is used with the win32 cgi-fcgi version of PHP 4.3.3 (standalone) but can maybe also used with a webserver and php (on win32 systems). It's working for me, maybe there are some bugs, but if it helps you to use oo in php or other languages,...

Bye
Björn Kalkbrenner, Rother-DATA GmbH

Code:

<?php
/*
Author: Bjoern Kalkbrenner <terminar@cyberphoria.org>
PHP OpenOffice Writer Example with Text Templates
Snipplets from oooforums.org and the SDK.
*/

    $rtpl="";
    $useremote=0;
   
    die("configure the path to the <SDKPATH>\examples\DevelopersGuide\Text\TextTemplateWithUserFields.sxw file and comment this line out");
   
    //$fname = "private:factory/swriter";
    echo("Using the TextTemplateWithUserFields.sxw templatefile form the SDK.\n");
   $fname = "file:///c|/php/test.sxw";
   
    echo("Starting COM");
    $osm = new COM("com.sun.star.ServiceManager") or die ("Local ServiceManager not initialized\n");
    echo("Lokaler ServiceManager initialized\n");

if (isset($useremote) && $useremote != 0)
{
    echo("Using Remote connection\n");
   
    $resolv = $osm->createInstance("com.sun.star.bridge.UnoUrlResolver") or die ("Resolver not initialized\n");
    echo("Resolver initialized\n");

    //$rosm = $osm->getRemoteServiceManager("uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager");

    $init = $resolv->resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager") or die ("Resolver not inizialized\n");
    echo("Resolver initialized\n");
   

    $context = $init->DefaultContext() or die ("Context not inizialized\n");
    echo("Remote context initialized\n");
   
    $rsm = $context->getServiceManager() or die ("Remote ServiceManager not initialized\n");
    echo("Remote ServiceManager initialized\n");


    $rdm = $rsm->createInstanceWithContext("com.sun.star.frame.Desktop",&$context) or die ("Remote Desktop not initialized\n");
     echo("Remote Desktop initialized\n");
     
     echo("Evaluating remote desktop components\n");
    $comps = $rdm->getComponents() or die ("GetComponents failed\n");
    $enum = $comps->createEnumeration() or die("createEnumeration of remote desktop components failed\n");

    while($enum->hasMoreElements() && $rtpl == "")
    {
        echo("New open Documents found\n");
        $c = $enum->nextElement();
        $cdocinfo = $c->getDocumentInfo();
        echo("Title: " . $cdocinfo->getPropertyValue("Title") . "\n");
        $rtpl = $c;
    }
   
} else
{
    echo("Not using remote connection. You can easily start OpenOffice Writer as Server with\n
    <path-to-openoffice>\programs\soffice.exe -accept=socket,port=8100;urp;\n
    It will sit in your systray as service even if you close the opened OpenOffice Window.\n
    You can control this with \n
    netstat -a -n \n
    and search for a listening port 8100. \n
    This is another solution to start oo as listen daemon additional to the steps mentioned in \n
    http://api.openoffice.org/docs/DevelopersGuide/FirstSteps/FirstSteps.htm#1+3+3+3+Make+the+office+listen\n
    ");
}



    $odm = $osm->createInstance("com.sun.star.frame.Desktop") or die("Local Desktop not initialized\n");
    echo("Local Desktop initialized\n");

    echo("Getting PropertyValue struct and set it to \"AsTemplate\"\n");
        $args=array();
        $prop1 = $osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue") or die("GetStruct failed\n");
        $prop1->Name="AsTemplate";
        $prop1->Value=1;
        $args[0]=$prop1;

   echo("---------------------\n\n");

if (isset($useremote) && $useremote != 0)
{
    echo("We use remote connection!\n");

    if (!$rdm)
    {
        //$odoc = $odm->loadComponentFromURL("private:factory/swriter", "_blank", 0, $args) or die("Document konnte nicht geladen werden\n");
        echo("Remote Desktop not initialized. Loading local document from local Desktop connection.\n");
        $rtpl = $odm->loadComponentFromURL(
            $fname,
            "_blank",
            0,
            $args) or die("Document can't be loaded from local Desktop connection\n");

    } else
    {
        if($rtpl=="")
        {
            echo("Remote desktop load, but document found in remote enumeration\n");
           
            echo("Document not loaded yet, loading remote document\n");
            $rtpl = $rdm->loadComponentFromURL(
                $fname,
                "_blank",
                0,
                $args) or die("Remote document not loaded.\n");
   
        } else
        {
            echo("Remote desktop enumeration already set opened document\n");
        }
       
    }
   
} //useremote


if ($rtpl=="")
{
    echo("Fallback check! No document loaded! Problem, but we load a document local\n");

    echo("No document loaded yet, loading local document.\n");
    $rtpl = $odm->loadComponentFromURL(
        $fname,
        "_blank",
        0,
        $args) or die("Local document not loaded. MAYBE FILE NOT FOUND?\n");
}


//resetting PropertyValue to NULL. This seem to prevent a memory problem on end of script.
$prop1=0;

    /*
    $xnfMasters=0;
    $xnfMasters = $otpl->getTextFieldMasters() or die("Failed to get TextFieldMasters\n");
    $xEnumFields=$otpl->getTextFields() or die("Failed to get TextFields\n");
    */
   
   echo("Evaluating static document fields\n");
    $fields = array(
    "Company" => "SomeCompany",
    "Contact" => "SomeContact",
    "City" => "SomeCity",
    "ZIP" => "SomeZIPCode",
    "State" => "SomeState"
    );

    reset($fields);
    while(list($key,$val) = each($fields))
    {
        echo("Getting Fieldmaster for $key\n");
        $field = $rtpl->TextFieldMasters->getByName("com.sun.star.text.FieldMaster.User." . $key);
       
        if (!$field)
        {

            echo ("Field not found, inserting field: $key\n");
            //field insert!
            $userfield = $rtpl->createInstance("com.sun.star.text.TextField.User") or die ("Textfield not initialized\n");
            $fieldmaster = $rtpl->createInstance("com.sun.star.text.FieldMaster.User") or die("Fieldmaster not initialized\n");
           
           
            if ($fieldmaster)
            {
                echo("Fields + Fieldmaster for field $key created\n");
                $fieldmaster->setPropertyValue("Name",$key);
                $fieldmaster->setPropertyValue("Content",$val);
           
                echo("Attaching Fieldmaster to Textfield\n");
                $userfield->attachTextFieldMaster($fieldmaster);
           
                echo("Getting position of cursor in the current active document\n");
                $text = $rtpl->getText();
                $cursor = $text->createTextCursor();

                echo("Inserting field to current cursor position\n");
                $text->insertTextContent($rtpl->CurrentController->getViewCursor(),$userfield,false);
           
            }
           
            $field = $fieldmaster;
       
        }
       
        echo("Getting PropertyContent via getPropertyValue: " );
        echo($field->getPropertyValue("Content") . "\n");

        echo("Getting PropertyContent via getPresentation: ");
        $os = $field->DependentTextFields();
        echo($os[0]->getPresentation(false) . "\n");

        echo("Setting Property to new value\n");
        $field->setPropertyValue("Content",$val);

    }


echo ("Inserting new temp testfield\n");
//field insert!
$userfield = $rtpl->createInstance("com.sun.star.text.TextField.User") or die ("Textfield nicht instanziert\n");
$fieldmaster = $rtpl->createInstance("com.sun.star.text.FieldMaster.User") or die("Fieldmaster not created\n");


if ($fieldmaster)
{
    echo("Fields + Fieldmaster created\n");
    $fieldmaster->setPropertyValue("Name",md5(uniqid("")));
    $fieldmaster->setPropertyValue("Content",md5(uniqid("")));

    echo("Attaching Fieldmaster to Tempfield\n");
    $userfield->attachTextFieldMaster($fieldmaster);

    echo("Getting position of cursor in the current active document\n");
    $text = $rtpl->getText();
    $cursor = $text->createTextCursor();
   

    echo("Inserting field to current cursor position\n");
    $text->insertTextContent($rtpl->CurrentController->getViewCursor(),$userfield,false);

}



$fieldmaster = $rtpl->TextFieldMasters->getByName("com.sun.star.text.FieldMaster.User.Company");

echo("DependentTextFields of Company\n");
$fields = $fieldmaster->DependentTextFields();
reset($fields);

echo("Are there dependent text fields?\n");
while(list($key,$val) = each($fields))
{
    echo("Field: " . $key . "\n");
    //true as argument would result in the command of the Textfield but you want the value so chose false.
    echo($val->getPresentation(false) . "\n");
}

echo("Enumerate all fields dynamically. Count: " . count($rtpl->TextFields) . "\n");
echo("----------------------------------------\n");
$fields = $rtpl->getTextFields();
$enum = $fields->createEnumeration();
while($enum->hasMoreElements())
{
    $elem = $enum->nextElement();
    echo("Key: " . $elem->getPresentation(true) . " Val:  " .  $elem->getPresentation(false) . "\n");
}

echo("this document can be printed automatically. Uncomment these lines.\n");
/*
    $args = array();
    $rtpl->print($args);
*/

echo("Dispose closes the document.\n");
//$rtpl->dispose();

echo("Done.");
?>


Back to top
View user's profile Send private message
goa103
OOo Advocate
OOo Advocate


Joined: 11 May 2003
Posts: 279

PostPosted: Sat Mar 19, 2005 3:51 am    Post subject: Re: Working Example: COM with PHP (Writer + TextFields...) Reply with quote

Terminar wrote:
since one week, i'm dealing with php, c++ and openoffice. Many articles in this forum were very helpful, but there was no fully working example.
I needed to do a php prototype for dealing with textfields and the swriter and here it is, thanks for the articles!

This example is used with the win32 cgi-fcgi version of PHP 4.3.3 (standalone) but can maybe also used with a webserver and php (on win32 systems). It's working for me, maybe there are some bugs, but if it helps you to use oo in php or other languages,...


What's the aim of the script ? It's quite long. Interesting, I didn't know we could COM with Writer using PHP !
_________________
An OOo mascot designer
Back to top
View user's profile Send private message
Cybb20
Super User
Super User


Joined: 02 Mar 2004
Posts: 1569
Location: Frankfurt, Germany

PostPosted: Mon Mar 21, 2005 10:10 am    Post subject: Reply with quote

The php example in my thread didn't work?
http://www.oooforum.org/forum/viewtopic.phtml?t=9815
Please give some more feedback on this, I would love to hear more about it.

Christian
_________________
- Knowledge is Power -
Back to top
View user's profile Send private message Send e-mail
goa103
OOo Advocate
OOo Advocate


Joined: 11 May 2003
Posts: 279

PostPosted: Tue Mar 22, 2005 1:45 am    Post subject: Reply with quote

Cybb20 wrote:
The php example in my thread didn't work?
http://www.oooforum.org/forum/viewtopic.phtml?t=9815
Please give some more feedback on this, I would love to hear more about it.


I will try to read your topic later. The test I did with PHP/COM for Word documents didn't work too. As mentionned in the manual it seems the COM functions are very alpha-beta.
_________________
An OOo mascot designer
Back to top
View user's profile Send private message
rjeggens
Newbie
Newbie


Joined: 09 Oct 2007
Posts: 1

PostPosted: Tue Oct 09, 2007 12:25 am    Post subject: Reply with quote

The script stops for me at:

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

with a timeout. What's wrong with it, or with my setup?
Back to top
View user's profile Send private message
my9381
Newbie
Newbie


Joined: 18 Apr 2011
Posts: 1

PostPosted: Mon Apr 18, 2011 5:53 pm    Post subject: me too! Reply with quote

the script didn't work untill I installed JDK.
Back to top
View user's profile Send private message MSN Messenger
Display posts from previous:   
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Macros and API All times are GMT - 8 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group