| View previous topic :: View next topic |
| Author |
Message |
christopher23 General User

Joined: 25 Feb 2010 Posts: 19
|
Posted: Thu Apr 08, 2010 6:32 am Post subject: unable to get createInstanceWithArguments working in PyUNO |
|
|
I'm having some trouble with PyUNO (Python) and createInstanceWithArguments. Somehow no Propertyvalues are being changed:
| Code: | from os.path import abspath
import uno, unohelper
from com.sun.star.text.TextContentAnchorType import AT_PARAGRAPH, AS_CHARACTER, AT_PAGE, AT_FRAME, AT_CHARACTER
from com.sun.star.beans import PropertyValue
from com.sun.star.task import ErrorCodeIOException
from com.sun.star.connection import NoConnectException
# Default port for OpenOffice
DEFAULT_OPENOFFICE_PORT = 8008
class DocumentConversionException( Exception ):
# Constructor
def __init__( self, message ):
self.message = message
def __str__( self ):
return self.message
class DocumentConversionException( Exception ):
# Constructor
def __init__( self, message ):
self.message = message
def __str__( self ):
return self.message
class DocumentConverter( object ):
# Constructor
def __init__(self, port=DEFAULT_OPENOFFICE_PORT):
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
try:
self.context = resolver.resolve("uno:socket,host=localhost,port=%s;urp;StarOffice.ComponentContext" % port)
except NoConnectException:
raise DocumentConversionException, "failed to connect to OpenOffice.org on port %s" % port
self.desktop = self.context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", self.context)
# Load component from URL
def loadComponent(self, **kwargs):
loadProperties = { "Hidden": True }
loadProperties.update(kwargs)
document = self.desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, self.toProperties(loadProperties))
return document
# Save file to System path
def saveFile(self, document, outputFile):
outputUrl = self.toFileUrl(outputFile)
outputExt = self.getFileExt(outputUrl)
storeProperties = self.getStoreProperties(document, outputExt)
try:
document.storeToURL(outputUrl, self.toProperties(storeProperties))
finally:
document.close(True)
# Returns a file-url for the given system path using Pythons absolute path
def toFileUrl(self, path):
return uno.systemPathToFileUrl(abspath(path))
# Create PropertyValues, and return them as tuple
def toProperties(self, dict):
props = list()
for key in dict:
prop = PropertyValue()
prop.Name = key
prop.Value = dict[key]
props.append(prop)
return tuple(props)
# Return file extension
def getFileExt(self, path):
ext = splitext(path)[1]
if ext is not None:
return ext[1:].lower()
# Detect what kind of file were handling
def detectFamily(self, document):
if document.supportsService("com.sun.star.text.WebDocument"):
return FAMILY_WEB
if document.supportsService("com.sun.star.text.GenericTextDocument"):
# must be TextDocument or GlobalDocument
return FAMILY_TEXT
if document.supportsService("com.sun.star.sheet.SpreadsheetDocument"):
return FAMILY_SPREADSHEET
if document.supportsService("com.sun.star.presentation.PresentationDocument"):
return FAMILY_PRESENTATION
if document.supportsService("com.sun.star.drawing.DrawingDocument"):
return FAMILY_DRAWING
raise DocumentConversionException, "unknown document family: %s" % document
# Return PropertyValues associated with the file we wan't to create
def getStoreProperties(self, document, outputExt):
family = self.detectFamily(document)
try:
propertiesByFamily = EXPORT_FILTER_MAP[outputExt]
except KeyError:
raise DocumentConversionException, "unknown output format: '%s'" % outputExt
try:
return propertiesByFamily[family]
except KeyError:
raise DocumentConversionException, "unsupported conversion: from '%s' to '%s'" % (family, outputExt)
def loadGraphicIntoDocument(self, document, url, internalName):
# Get the BitmapTable from this drawing document.
# It is a service that maintains a list of bitmaps that are internal to the document.
oBitmaps = document.createInstance("com.sun.star.drawing.BitmapTable")
# Add an external graphic to the BitmapTable of this document.
oBitmaps.insertByName(internalName, self.toFileUrl(url))
# What we get back is a different Url that points to a graphic
# which is inside this document, and remains with the document.
url = oBitmaps.getByName( internalName )
return url
def makePropertyValue( cName=None, uValue=None, nHandle=None, nState=None ):
# Create a com.sun.star.beans.PropertyValue struct and return it.
oPropertyValue = uno.createUnoStruct( "com.sun.star.beans.PropertyValue" )
if cName != None:
oPropertyValue.Name = cName
if uValue != None:
oPropertyValue.Value = uValue
if nHandle != None:
oPropertyValue.Handle = nHandle
if nState != None:
oPropertyValue.State = nState
return oPropertyValue
try:
# Load Class
oCreateDocument = DocumentConverter()
# Create document
oDoc = oCreateDocument.loadComponent()
# Get StyleFamilies
oPageStyles = oDoc.getStyleFamilies().getByName("PageStyles")
# New PageStyle, with Header and Footer
oStyle = oDoc.createInstanceWithArguments("com.sun.star.style.PageStyle",
( makePropertyValue( "HeaderIsOn", True ),
makePropertyValue( "FooterIsOn", True ), ) )
oPageStyles.insertByName( "TitlePage", oStyle )
print oStyle.getPropertyValue('HeaderIsOn')
except DocumentConversionException, exception:
# Show error message
print "Error: %s" % str(exception)
exit(1)
except ErrorCodeIOException, exception:
# Show error message
print "ErrorCodeIOException: %s" % exception.ErrCode
exit(1) |
If you try this code (copy/paste and it should work) you will see it says: False
but with makePropertyValue( "HeaderIsOn", True ) it should say True.
Although when I do:
oStyle.HeaderIsOn = True
it works, but with createInstanceWithArguments() it somehow doesn't
I hope somebody can help me with this one. |
|
| Back to top |
|
 |
christopher23 General User

Joined: 25 Feb 2010 Posts: 19
|
Posted: Fri Apr 09, 2010 1:33 am Post subject: |
|
|
| I still hope somebody can help me out on this one.. Java and Basic examples are welcome as well.. |
|
| Back to top |
|
 |
hanya Super User

Joined: 04 May 2005 Posts: 543 Location: Japan
|
Posted: Fri Apr 09, 2010 4:07 am Post subject: |
|
|
In Basic: | Code: | Sub makestyle
arg = CreateUnoStruct("com.sun.star.beans.PropertyValue")
arg.Name = "HeaderIsOn"
arg.Value = True
arg2 = CreateUnoStruct("com.sun.star.beans.PropertyValue")
arg2.Name = "FooterIsOn"
arg2.Value = True
oDoc = ThisComponent
oStyle = oDoc.createInstanceWithArguments("com.sun.star.style.PageStyle", _
Array(arg, arg2))
msgbox oStyle.HeaderIsOn ' False
End Sub |
In Java: | Code: | package macro;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.script.provider.XScriptContext;
import com.sun.star.lang.IndexOutOfBoundsException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
public class Test {
static public void call_snippet(XScriptContext xScriptContext)
{
Object doc = xScriptContext.getDocument();
snippet(doc);
}
static public void snippet(Object oInitialTarget)
{
try
{
PropertyValue[] args = new PropertyValue[2];
args[0] = new PropertyValue();
args[0].Name = "HeaderIsOn";
args[0].Value = true;
args[1] = new PropertyValue();
args[1].Name = "FooterIsOn";
args[1].Value = true;
XMultiServiceFactory xMSF = UnoRuntime.queryInterface(XMultiServiceFactory.class, oInitialTarget);
Object style = xMSF.createInstanceWithArguments("com.sun.star.style.PageStyle", args);
XPropertySet xPropSet = UnoRuntime.queryInterface(XPropertySet.class, style);
System.out.println(xPropSet.getPropertyValue("HeaderIsOn")); // false
}
catch (WrappedTargetException e1)
{
e1.printStackTrace();
}
catch (IndexOutOfBoundsException e2)
{
e2.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
static public void main()
{
System.out.println("main");
}
} |
|
|
| Back to top |
|
 |
christopher23 General User

Joined: 25 Feb 2010 Posts: 19
|
Posted: Fri Apr 09, 2010 4:41 am Post subject: |
|
|
| Your basic example looks very similar to my Python code... So I don't understand my HeaderIsOn doesn't change to True. |
|
| Back to top |
|
 |
hanya Super User

Joined: 04 May 2005 Posts: 543 Location: Japan
|
Posted: Fri Apr 09, 2010 5:17 am Post subject: |
|
|
| Code: | | So I don't understand my HeaderIsOn doesn't change to True. |
My basic code gets false and it does not support argument setting at the creation of new instance. See sw/source/ui/uno/unotxdoc.cxx. |
|
| Back to top |
|
 |
|
|
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
|